头文件–必须加
#include<string>
长度
s.length();//字符串中字符个数
s.size();//同上
s.capacity()//表示当前string的容量,即开辟内存的大小
读写
string str;//定义后,为长度为0的空串
cin >> str;//空格即结束
cout << str;
赋值
string s1,s2;
s1 = "hello world";
s2 = s1;
cout << s1 << endl;
cout << s2 << endl;//输出hello world
连接
//使用+ 和 +=
string s1 = "Atlas ",s2 = "King",s3;
s3 = s1 + s2;
s1 += s2;
cout << s1 << endl;
cout << s3 << end; //均输出Atlas King
修改
erase(4,7); //第一个数为要删除子串的开始位置,后一个数为长度
*注:是对自身进行操作
插入
s.insert(4,s2); //第一个参数为插入位置,第二参数给出要插入的字符串
注:1.修改自身;2.第二个字符串也可以是C风格的字符数组
替换
s.replace(4,6,s2); //1为开始为位置,2为长度,3为要替代的字符串
交换
string s1 = "I";
string s2 = "You";
s1.swap(s2);
cout << s1 << endl; //输出You
cout << s2 << endl;//输出 I
提取子串
s.substr(4,6);
//1为开始为位置,2为子串长度。若长度超出,则直接取原字符串从开始位置后的全部即可
查找
int number= s.find(s2,ind); //返回首字母的序号【未找到,返回-1】
//查找从位置ind之后【包括ins】的部分中,子串s2的位置。若ind缺省,则默认为零,即在整个串中查找
字符串比较
if(s1 == s2) //区分大小写
if(s1 < s2)
if(s1 != s2)
大小写转换
【3.std::string 转换大小写】
很遗憾,std::string 没有提供大小写转换的功能,所以只能用STL中的transform结合toupper/tolower完成。
头文件: string, cctype,algorithm
转小写
//转小写
transform(str.begin(),str.end(),str.begin(),tolower);
transform(wstr.begin(), wstr.end(), wstr.begin(), towlower);
//转大写
transform(s.begin(), s.end(), s.begin(), toupper);
transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);
Example:
wstring wstr =L"Abc";
transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);
排序函数sort()
https://zhidao.baidu.com/question/216527176.html
逆置
char str[]="abcdefgh";//【变成"abgfedch"】
reverse(str+2,str+7);//对字符串数组
string s=str;
reverse(s.begin()+2,s.begin()+7);//对string
//reverse(s.begin()+2,s.end()-1);//和上面一句效果一样