1. 運算符重載
- +、+= 連接字符串
- = 字符串賦值
- >、>=、<、<= 字符串比較(例如a < b, aa < ab)
- ==、!= 比較字符串
- <<、>> 輸出、輸入字符串
注意:使用重載的運算符 + 時,必須保證前兩個操作數至少有一個為 string 類型。例如,下面的寫法是不合法的:
1 #include <iostream> 2 #include <string> 3 int main() 4 { 5 string str = "cat"; 6 cout << "apple" + "boy" + str; // illegal! 7 return 0; 8 }
2. 字符串查找
2.1 find() 查找函數
1 str.find("ab"); 2 //返回字符串 ab 在 str 的位置 3 str.find("ab", 2); 4 //在 str[2]~str[n-1] 范圍內查找並返回字符串 ab 在 str 的位置 5 str.rfind("ab", 2); 6 //在 str[0]~str[2] 范圍內查找並返回字符串 ab 在 str 的位置
2.2 find_first() 首次出現系列函數
1 str.find_first_of("apple"); 2 //返回 apple 中任何一個字符首次在 str 中出現的位置 3 str.find_first_of("apple", 2); 4 //返回 apple 中任何一個字符首次在 str[2]~str[n-1] 范圍中出現的位置 5 str.find_first_not_of("apple"); 6 //返回除 apple 以外的任何一個字符在 str 中首次出現的位置 7 str.find_first_not_of("apple", 2); 8 //返回除 apple 以外的任何一個字符在 str[2]~str[n-1] 范圍中首次出現的位置
2.3 find_last() 末次出現系列函數
1 str.find_last_of("apple"); 2 //返回 apple 中任何一個字符最后一次在 str 中出現的位置 3 str.find_last_of("apple", 2); 4 //返回 apple 中任何一個字符最后一次在 str[0]~str[2] 范圍中出現的位置 5 str.find_last_not_of("apple"); 6 //返回除 apple 以外的任何一個字符在 str 中最后一次出現的位置 7 str.find_last_not_of("apple", 2); 8 //返回除 apple 以外的任何一個字符在 str[0]~str[2] 范圍中最后一次出現的位置
注意:以上函數如果沒找到的話均返回 string::npos。
3. 字符串的子串
1 str.substr(3); 2 //返回 [3] 及以后的子串 3 str.substr(2, 4); 4 //返回 str[2]~str[2+(4-1)] 子串(即從[2]開始4個字符組成的字符串)
4. 字符串替換
1 str.replace(2, 4, "sz"); 2 //返回把 [2]~[2+(4-1)] 的內容替換為 "sz" 后的新字符串 3 str.replace(2, 4, "abcd", 3); 4 //返回把 [2]~[2+(4-1)] 的內容替換為 "abcd" 的前3個字符后的新字符串
5. 字符串插入
1 str.insert(2, "sz"); 2 //從 [2] 位置開始添加字符串 "sz",並返回形成的新字符串 3 str.insert(2, "abcd", 3); 4 //從 [2] 位置開始添加字符串 "abcd" 的前 3 個字符,並返回形成的新字符串 5 str.insert(2, "abcd", 1, 3); 6 //從 [2] 位置開始添加字符串 "abcd" 的前 [2]~[2+(3-1)] 個字符,並返回形成的新字符串
6. 字符串追加
除了用重載的 +
操作符,還可以使用函數來完成。
1 str.push_back('a'); 2 //在 str 末尾添加字符'a' 3 str.append("abc"); 4 //在 str 末尾添加字符串"abc"
7. 字符串刪除
1 str.erase(3); 2 //刪除 [3] 及以后的字符,並返回新字符串 3 str.erase(3, 5); 4 //刪除從 [3] 開始的 5 個字符,並返回新字符串
8. 字符串交換
1 str1.swap(str2); 2 //把 str1 與 str2 交換
9. 其他函數
1 str.size(); 2 //返回字符串長度 3 str.length(); 4 //返回字符串長度 5 str.empty(); 6 //檢查 str 是否為空,為空返回 1,否則返回 0 7 str[n]; 8 //存取 str 第 n + 1 個字符 9 str.at(n); 10 //存取 str 第 n + 1 個字符(如果溢出會拋出異常)
部分參考:https://www.renfei.org/blog/introduction-to-cpp-string.html