c++ string 操作匯總

歡迎訪問我的個人博客:zengzeyu.com

前言


作為傳遞信息的載體string數據類型廣泛應用于各種編程語言中,尤其在輕量化語言 Python 中發揮的淋漓盡致,通過string傳遞信息 Python 使各個模塊組裝在一起完成指定的工作任務,這也是 Python 被稱為“膠水語言”的原因。
本文著眼于 c++string的應用。首先建議先瀏覽string在線文檔,這其中包含了大多數日常所需函數。

正文


1. string 內查找字符串str

std::string::find(str)函數:http://www.cplusplus.com/reference/string/string/find/
Example

// string::find
#include <iostream>       // std::cout
#include <string>         // std::string

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

  return 0;
}

其中 npos 值為 -1,用于判斷。
其他查找功能類函數:

  • rfind: 找到目標str最后一次出現位置
  • find_first_of: 從起始位置查找目標str
  • find_last_of: 從結束位置往回查找目標str

2. string內刪除目標str

substr: 本質還是查找目標str
Example

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

3. 字符串分割

字符串分割推薦使用 std::stringstream 作為中間載體和 getline() 函數組合來完成。
以分割字符 “ ; ”為例:

void splitPathStr(std::string& path_str)
{
    std::vector<std::string> filelists;
    std::stringstream sstr( path_str );
    std::string token;
    while(getline(sstr, token, ';'))
    {
        filelists.push_back(token);
    }
}

4. int型與string型互相轉換

int型轉string

void int2str(const int &int_temp,string &string_temp)  
{  
        stringstream stream;  
        stream<<int_temp;  
        string_temp=stream.str();   //此處也可以用 stream>>string_temp  
}  

string型轉int

void str2int(int &int_temp,const string &string_temp)  
{  
    stringstream stream(string_temp);  
    stream>>int_temp;  
} 

未完待續...

以上。


參考文獻:

  1. c++ reference
  2. C++中int、string等常見類型轉換
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容