首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C++ STL string 常用方法完整速查手冊

     編輯:關於C語言

前言

std::string 是 C++ 處理字串的標準利器。本文按功能分類彙總 9 大類常用方法,附帶簽名與語意說明,作為開發時的快速參考。

1. 賦值與構造 assign / operator=

  • string& operator=(const string& s)
  • string& assign(const char* s)
  • string& assign(const char* s, int n) 前 n 字符
  • string& assign(const string& s)
  • string& assign(int n, char c) n 個字符 c
  • string& assign(const string& s, int pos, int n) 子串
  • string& assign(iterator first, iterator last) 迭代器區間

2. 追加 append / operator+=

  • string& operator+=(const string& s)
  • string& append(const char* s)
  • string& append(const char* s, int n)
  • string& append(const string& s)
  • string& append(const string& s, int pos, int n)
  • string& append(int n, char c)
  • string& append(iterator first, iterator last)

3. 比較 compare / 運算子

  • bool operator==(const string& s1, const string& s2) 等比較運算子全支援
  • int compare(const string& s) const 整串比較
  • int compare(int pos, int n, const string& s) const 子串比較
  • int compare(int pos, int n, const string& s, int pos2, int n2) const 雙子串比較
  • 同系列 const char* 重載
  • 回傳:>0 返回 1,<0 返回 -1,=0 返回 0

4. 查找 find / rfind / find_first/last_of/not_of

所有方法支援 char、const char*、string、pos、n 多重載。

5. 插入 insert

  • 位置 + 字串/字符:insert(pos, str)、insert(pos, n, c)
  • 迭代器版本:insert(it, c)、insert(it, first, last)、insert(it, n, c)

6. 刪除 erase

  • iterator erase(iterator first, iterator last) 區間刪除
  • iterator erase(iterator it) 單字符刪除
  • string& erase(int pos = 0, int n = npos) 位置長度刪除

7. 替換 replace

  • 位置長度 + 字串/字符:replace(pos, len, str)、replace(pos, len, n, c)
  • 迭代器區間 + 字串/字符/區間:replace(first0, last0, str) 等 5 種重載

8. 子串 substr

  • string substr(int pos = 0, int n = npos) const 返回新字串

9. 交換 swap

  • void swap(string& s2) 常數時間交換內容

使用提醒

  • 所有修改操作會使迭代器/指標/引用失效
  • c_str()/data() 獲取 C 風格字串指標
  • 優先使用 string 而非 char*,享受 RAII 與邊界檢查(at())

本文為方法速查彙總,詳細行為請參考 C++ 標準庫文檔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方法族方向用途失敗回傳
find左→右查找字符/字串首次出現位置string::npos
rfind右→左查找最後一次出現位置
find_first_of左→右查找首個屬於指定字符集的字符
find_first_not_of左→右查找首個不屬於指定字符集的字符
find_last_of / not_of右→左反向版本