总结一下C++中String的方法
运算符重载
符号 |
作用 |
+, += |
连接字符串 |
= |
字符串赋值 |
>, >=, <, <= |
字符串比较 |
==, != |
比较字符串 |
<<, >> |
输入,输出字符串 |
常用函数
1 2 3
| cout << str.size() << endl; cout << str.length() << endl; cout << str.empty() << endl;
|
测试与返回结果如下所示:
查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| string str; cin >> str;
cout << str.find("test") << endl ; cout << str.find("test", 2) << endl; cout << str.rfind("test", 2) << endl; cout << endl; cout << str.find_first_of("strTest") << endl; cout << str.find_first_of("strTest", 2) << endl; cout << str.find_first_not_of("strTest") << endl; cout << str.find_first_not_of("strTest", 2) << endl; cout << endl; cout << str.find_last_of("strTest") << endl; cout << str.find_last_of("strTest", 2) << endl; cout << str.find_last_not_of("strTest") << endl; cout << str.find_last_not_of("strTest", 2) << endl; cout << endl; cout << string::npos;
|
测试与返回结果如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 0123test89strTest //测试数据,以下依次为结果 4 4 4294967295
4 4 0 2
16 4294967295 9 2
4294967295
|
子串
1 2
| cout << str.substr(3) << endl; cout << str.substr(2, 4) << endl;
|
测试与返回结果如下所示:
1 2 3
| myStringTest //测试数据,以下依次为结果,下同 tringTest Stri
|
替换
1 2
| cout << str.replace(2, 4, "test") << endl; cout << str.replace(2, 4, "qwer", 3) << endl;
|
测试与返回结果如下所示:
1 2 3
| yyyyyyyyyyyyyy yytestyyyyyyyy yyqweyyyyyyyy
|
插入
1 2 3
| cout << str.insert(2, "test") << endl; cout << str.insert(2, "string", 3) << endl; cout << str.insert(2, "123456", 1, 3) << endl;
|
测试与返回结果如下所示:
1 2 3 4
| yyyyyyyyy yytestyyyyyyy yystrtestyyyyyyy yy234strtestyyyyyyy
|
追加
1 2 3
| str.push_back('1'); cout << str << endl; cout << str.append("abc") << endl;
|
测试与返回结果如下所示:
删除
1 2 3
| string str1 = str; cout << str.erase(3) << endl; cout << str1.erase(3, 5) << endl;
|
测试与返回结果如下所示:
交换
1 2 3 4 5 6
| string str1, str2; cin >> str1; cin >> str2; str1.swap(str2); cout << endl; cout << str1 << endl << str2 << endl;
|
测试与返回结果如下所示:
1 2 3 4 5
| 123456 qwerty
qwerty 123456
|
参考文献
C++ string 字符串函数详解
string - C++ Reference