@RabbitHu 2017-09-19T07:33:43.000000Z 字数 2006 阅读 6666

十个你一定会用到的 C++ string 函数！

笔记

目录

1. 赋值         6. 交换
2. 长度         7. 子串
3. 比较         8. 替换
4. 查找         9. 插入
5. 连接         10. 删除

赋值

1. 字符串1 = 字符串2;
2. 字符串1.assign(字符串2);

string s1 = "I'm ";string s2;s2 = "1234Juruo1234";s1.assign(s2);cout << s1;//输出结果：1234Juruo1234

string s1 = "I'm ";string s2 = "1234Juruo1234";s1.assign(s2, 4, 5);cout << s1;//输出结果:Juruo

长度

1. 字符串1.length();
2. 字符串1.size();

string s1 = "1234Juruo1234";cout << s1.length() << endl;cout << s1.size() <<endl;/*输出结果：1313*/

比较

">", "<", "==", ">=", "<="均可以用于字符串比较。

string PPAP[] = {"I", "have", "a", "pen", "an", "apple", "um", "apple-pen"};sort(PPAP, PPAP + 8);for(int i = 0; i < 8; i++){    cout << PPAP[i] << endl;}/*输出结果：Iaanappleapple-penhavepenum*/

查找

string s1 = "ggabcdabcgggabcdefg";string s2 = "gg";int pos = -1;while(1){    pos = s1.find(s2, pos+1);    if(pos == -1) break;    cout << pos << ' ';}//输出结果：0 9 10 

string s1 = "ggabcdabcgggabcdefg";string s2 = "gg";int pos = s1.length();while(pos > 0){    pos = s1.rfind(s2, pos-1);    if(pos < 0) break;    cout << pos << ' ';}//输出结果：10 9 0;

连接

1. 字符串1.append(字符串2); //字符不可
2. 字符串1 += 字符串2; //字符亦可

string s1 = "I'm ";string s2 = "Juruo";s1.append(s2);// 或 s1 += s2;cout << s1;//输出结果：I'm Juruo

string s1 = "I'm ";string s2 = "1234Juruo1234";s1.append(s2, 4, 5);cout << s1;//输出结果：I'm Juruo

交换

string s1 = "I'm ";string s2 = "Juruo";s1.swap(s2);cout << s1 << endl;//输出结果：Juruo

子串

string s1 = "I'm ";string s2 = "1234Juruo1234";s1 = s2.substr(4, 5);cout << s1 << endl;//输出结果：Juruo

替换

string s1 = "I'm Juruo";string s2 = "Juruo";string s3 = "Dalao";int pos = s1.find(s2);s1.replace(pos, s2.length(), s3);cout << s1;//输出结果：I'm Dalao

插入

string s1 = "I'm Juruo";string s2 = "not ";s1.insert(s1.find("Juruo", 0), s2 );cout << s1 << endl;//输出结果：I'm not Juruo

删除

string s1 = "I'm not Dalao";s1.erase(s1.find("not"), 4);cout << s1 << endl;

• 私有
• 公开
• 删除