1. string赋值操作
#include<iostream> #include<string> using namespace std; int main() { string str1; str1.assign("laozhichi niubi"); cout << str1 << endl; string str2; str2.assign("laozhichi", 5); cout << str2 << endl; string str3; str3.assign(10, 'x'); cout << str3 << endl; return 0; }
2.string字符串拼接
string& append(const char *s, int n); //把字符串s的前n个字符连接到当前字符串结尾
string& append(const string &s, int pos, int n); //字符串s中从pos开始的n个字符连接到字符串结尾
#include<iostream> #include<string> using namespace std; int main() { string str = "laozhichi"; str += "zuiniubi"; str.append("diaomao"); str.append("diaomao", 4); str.append("caonimad", 4, 3); cout << str << endl; return 0; }
3.string查找和替换
#include<iostream> #include<string> using namespace std; void test() { string str = "laozhichi"; str.replace(1, 3, "diaonimade"); cout << str << endl; } int main() { string str = "laozhichi"; int result = str.find("zhi"); if (result == -1) { cout << "not find" << endl; } else { cout << "result=" << result << endl; }; test(); return 0; }
4.string字符串比较
#include<iostream> #include<string> using namespace std; void compare() { string str = "laozhichi"; string str1 = "diaonima"; int result = str.compare(str1); if (result == 0) { cout << "s1==s2"; } else if(result>0) { cout << "s1>s2" << endl; } else { cout << "s1<s2" << endl; } } int main() { compare(); return 0; }
5.string插入和删除
#include<iostream> #include<string> using namespace std; void get() { string str = "laozhichi"; str.insert(1, "laozhichiniubi"); cout << str << endl; str.erase(1, 5); cout << str << endl; } int main() { get(); return 0; }
6.string字串
#include<iostream> #include<string> using namespace std; void get() { string str = "laozhichi"; string str1 = str.substr(1, 3); cout << str1 << endl; } int main() { get(); return 0; }