1、标准库string类型
2、string对象的定义和初始化
#include <string>
#include <iostream>
using namespace std;
int main() {
string s1;
string s2("abcdefghijklmn");
cout << s2 << endl;
basic_string<char> s3("xxxx"); // basic_string<char> 等价于string,其实string 就是一个模板,basic_string<char> 是它的原型
cout << s3 << endl;
string s4("abcdefg", 4);
cout << s4 << endl;
string s5(s2, 2, 3);
cout << s5 << endl;
string::iterator first = s2.begin() + 1;
string ::iterator last = s2.begin() + 3;
string s6(first, last); // [first, last)
cout << s6 << endl;
return 0;
}
// 输出
abcdefghijklmn
xxxx
abcd
cde
bc
3、常用的成员函数
#include <string>
#include <iostream>
using namespace std;
int main() {
string s1("abcdefghi");
cout << s1.size() << endl;
cout << s1.length() << endl;
cout << s1.empty() << endl;
cout << s1.substr(1, 2) << endl;
cout << s1.substr(1) << endl;
string::size_type pos = s1.find('d', 1);
if(pos == string::npos)
{
cout << "not found" << endl;
}
else
{
cout << "pos = " << pos << endl;
}
pos = s1.rfind('d');
if(pos == string::npos)
{
cout << "not found" << endl;
}
else
{
cout << "pos = " << pos << endl;
}
return 0;
}
// 输出
9
9
0
bc
bcdefghi
pos = 3
pos = 3
#include <string>
#include <iostream>
using namespace std;
int main() {
string s1("abcdefghijkl");
s1.replace(2, 2, "AAAAA");
cout << s1 << endl;
s1 = "abcdefg";
s1.replace(s1.begin() + 1, s1.begin() + 4, "BBBBB");
cout << s1 << endl;
string s2 = "xyzabc";
s2.insert(2, "FFFFFF");
cout << s2 << endl;
s2.append("7777777777");
cout << s2 << endl;
string s3 = "111";
s2.swap(s3);
cout << s2 << endl;
cout << s3 << endl;
return 0;
}
// 输出
abAAAAAefghijkl
aBBBBBefg
xyFFFFFFzabc
xyFFFFFFzabc7777777777
111
xyFFFFFFzabc7777777777
#include <string>
#include <iostream>
using namespace std;
void fun(char* str)
{
cout << str << endl;
}
int main() {
string s1 = "abc";
s1[1] = 'B';
cout << s1 << endl;
const string s2 = "xyz";
//s2[1] = 'Y'; // function 'operator[]' returns a const value
string s3 = "132" + s1 + "6547";
cout << s3 << endl;
fun(const_cast<char*>(s3.c_str()));
return 0;
}
// 输出
aBc
132aBc6547
132aBc6547
4、常用的成员函数