C++常用string函数

来自https://www.cnblogs.com/jm-Xu/p/9318705.html

string(s小写)是C++标准库中的类,纯C中没有,使用时需要包含头文件#include<string>

1 string的定义及初始化
2 string s1 = "hello"; //初始化字符串
3 string s2 ("world"); //另一种初始化 
4 
5 string s3;   //初始化字符串,空字符串
6 
7 string s4(5, 'a'); //s4由连续5个a组成,即s4="aaaaa";
8 string s5(s1,2,3); //从s1的2位置的字符开始,连续3个字符赋值给s5,即s5="llo";
9 string s6(s1, 1); //从s1的2位置的字符开始,将后续的所有字符赋值给s6,即s6="ello"; 
 1 重载的运算符
 2 此处列举一下被重载的运算符,基本意思一目了然。其中注意“+”操作 
 3     s1 = s2;
 4     s1 += s2;
 5     s1 = s2 + s3;
 6     s1 == s2;
 7     s1 = "s" + s2; //正确
 8     s1 = "s" + "s"; //错误,加号两边至少要有一个string类型的对象
 9     s1 = "s" + s2 + "s" + "s"; //正确
10 
11 “+”的两边要保证至少有一个string类型,所以5正确,6错误。由于在C/C++中,+的返回值还是原类型,所以第7行中,"s"+s2返回一个string类型,因此string+“s”也是正确的,
 1 遍历string(迭代器)
 2 遍历string中的元素时,我们可以使用类似C中的数组形式访问,如s1[1](下标从0开始)
 3 
 4 也可以使用STL特有的迭代器访问:
 5 string::iterator it;
 6 for (it = s1.begin(); it != s1.end(); it++){
 7     cout << *it << endl;
 8 }
 9 
10 cout << *(s1.begin()); //正确,即访问s1[0]
11 cout << *(s1.end()); //错误,s1.end()指向了空
12 若想要从后向前遍历string时,可以用到rbegin()和rend()函数。
13 (参考vector博文)

1 插入insert()
2 string s1 = "hello";
3 s1.insert(1,"ins"); //从s1的1位置开始,插入"ins"字符串,即s1="hinsello";
4 s1.insert(1, "ins", 2);//从s1的1位置开始,插入"ins"字符串的前2个字符,即s1="hinello";
5 s1.insert(1, "ins", 1, 2);//从s1的1位置开始,插入"ins"字符串的从1位置开始的2个字符,即s1="hnsello";
6 
7 iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置
 1 删除erase()
 2 iterator erase(iterator first, iterator last);//删除[first,last)之间的所有字符,返回删除后迭代器的位置
 3 iterator erase(iterator it);//删除it指向的字符,返回删除后迭代器的位置
 4 string &erase(int pos = 0, int n = npos);//删除pos开始的n个字符,返回修改后的字符串
 5 
 6 
 7 查找 find()
 8 cout << s.find("aa", 0) << endl; //返回的是子串位置。第二个参数是查找的起始位置,如果找不到,就返回string::npos
 9 if (s.find("aa1", 0) == string::npos)
10 {
11     cout << "找不到该子串!" << endl;
12 }
原文地址:https://www.cnblogs.com/adelalove/p/11831809.html