歡迎訪問我的個人博客: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等常見類型轉換