string的构造函数的形式:
string str:生成空字符串
string s(str):生成字符串为str的复制品
string s(str, stridx):将字符串str中始于stridx的部分,复位构造函数的初值
string s(str, strbegin, strlen):将字符串str中始于strbegin、长度为strlen的部分作为字符串初值
string s(cstr):以C_string类型cstr作为字符串s的初值
string s(cstr, char_len):以C_string类型cstr的前char_len个字符串作为字符串s的初值
string str1; //生成空字符串
string str2("1234"); //生成"1234"的复制品
string str3("12345", 1, 3);//结果为"234"
string str4("123456", 5); //结果为"12345"
string str5(5, '1'); //结果为"11111"
string str6(str2, 2); //结果为"34"
大小和容量:
-
size()和length():返回string对象的字符个数,他们执行效果相同。
-
max_size():返回string对象最多包含的字符数,超出会抛出length_error异常
-
capacity():重新分配内存之前,string对象能包含的最大字符数
string s("1234567");
cout << "size=" << s.size() << endl;
cout << "length=" << s.length() << endl;
cout << "max_size=" << s.max_size() << endl;
cout << "capacity=" << s.capacity() << endl;
结果:
size=7
length=7
max_size=4294967294
capacity=15
compare() 函数,比较运算符:> , < , == , <=, >=
string A("aBcdef");
string B("AbcdEf");
string C("123456");
string D("123dfg");
int m = A.compare(B);
int n = A.compare(1, 5, B);
int p = A.compare(1, 5, B, 4, 2);
int q = A.compare(0, 3, D, 0, 3);
cout << "m=" << m << endl;
cout << "n=" << n << endl;
cout << "p=" << p << endl;
cout << "q=" << q << endl;
result:
m=1
n=1
p=-1
q=1
assign()函数:直接给字符串赋值。
string str7("123456");
string str;
str.assign(str7);
cout << str << endl;
str.assign(str7, 3, 3);
cout << str << endl;
str.assign(str7, 2, str7.npos);
cout << str << endl;
str.assign(5, 'X');
cout << str << endl;
string::iterator itB = str7.begin();
string::iterator itE = str7.end();
str.assign(itB, --itE);
cout << str << endl << endl;
结果:
123456
456
3456
XXXXX
12345
erase():删除函数
sawp()函数:相互交换字符串
insert()函数:在字符串中某个位置插入其他字符串
str = "01234567";
str.insert(1, "abc");
cout << str << endl;//out:0abc1234567
str.insert(1, "edfg", 3);
cout << str << endl;//out:0edfabc123467
str = "01234";
str.insert(1, "abcde", 2, 3);
cout << str << endl << endl;//out:0cde1234
append()函数:在字符串最后面追加其他字符串。
replace()函数:用其他字符串替换字符串中的某个子串。
find()函数:从首部开始查找字符串,返回查找到的子串在字符串中的第一个字符的位置
rind()函数:从首部开始查找字符串,返回查找到的子串在字符串中的第一个字符的位置
find_first_of()函数:在源字符串搜索某字符串,返回被搜索字符串中第一个字符第一次出现的下标。
find_last_of()函数:功能同上,返回被搜索字符串中最后一个字符的下标。
string str = "hxh1323121678feifeihxhdian456";;
size_t index1 = str.find("hxh");
size_t index2 = str.find_last_of("hxh");
cout << index1 << "\t" << index2 << endl;
结果:
0 21