二、C++ STRING 常用操作整理
操作 说明 使用例子 s2 = s1 将 s1 的内容赋给 s2(若 s2 原来有内容,则直接覆盖) string s1 = "hello"; string s2; s2 = s1; // s2 变为 "hello" s1 + s2 把 s1 和 s2 连接成一个新字符串,返回新生成的字符串 string a = "abc"; string b = "def"; string c = a + b; // c = "abcdef" s1 += s2 把 s2 拼接在 s1 后面 string s = "hello"; s += " world"; // s = "hello world" s1
== s2 比较 s1 与 s2 的内容,相等则返回 true,否则返回 false if (s1 == s2) cout << "相等"; // 比较两个字符串内容是否相同 !=, <, <=, >, >= 保持这些操作符惯有的含义,比较大小时按照字典序进行比较 if (s1 < s2) cout << "s1 排在前面"; // "abc" < "abd" 返回 true s.size() / s.length() 返回 s 中字符的个数,也称为字符串的大小 string s = "hello"; int len = s.size(); // len = 5 int len2 =
s.length(); // 也是 5 s.empty() 如果 s 为空串,则返回 true,否则返回 false string s; if (s.empty()) cout << "字符串为空"; // 输出"字符串为空" s.insert(pos, s2) 在 s 下标为 pos 的元素前插入 string 类型 s2 string s = "hello"; s.insert(2, "123"); // s 变为 "he123llo" s.substr(pos, len) 返回一个 string 类型,它包含 s 中下标为 pos 起的 len 个字符 string s = "hello
world"; string sub = s.substr(6, 5); // sub = "world" s.erase(pos, len) 删除 s 中下标为 pos 开始的 len 个字符 string s = "hello world"; s.erase(5, 6); // s 变为 "hello" s.replace(pos, len, s2) 删除 s 中下标为 pos 的 len 个字符,并在下标为 pos 处插入 s2(即替换) string s = "I like C"; s.replace(7, 1, "C++"); // s 变为 "I like C++"
s.find(s2, pos) 在 s 中下标为 pos 的位置起查找 s2 第一次出现的下标,若查找不到返回 string::npos string s = "hello world"; int pos = s.find("world", 0); if (pos != string::npos) cout << "找到了,位置:" << pos; // 输出:找到了,位置:6 s.clear() 清空 s 中的内容 string s = "hello"; s.clear(); // s 变为空字符串 "" reverse(s.begin(), s.end()) 将字符串 s 反转(需要包含
<algorithm> 头文件) #include <algorithm> string s = "hello"; reverse(s.begin(), s.end()); // s 变为 "olleh"
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------