在這篇短文中,我想分享一段簡短的程式碼,關於如何像 PHP 程式語言中那樣分割字串。我們知道,在 PHP 中有一個名為 explode() 的函式,可以用給定的分隔符(單個字元或子字串)來分割字串。例如,給定一個字串 str = "the quick brown fox",它將被 " " (空格字元) 分割。我們只需呼叫 explode(str, " "),該函式就會返回字串陣列 {"the", "quick", "brown", "fox"}。
我們可以用 C++ 編寫一個類似“PHP explode()”的函式,不過給定的分隔符僅限單個字元。我們的 explode() 版本會返回 std::vector<string> 作為分割後的字串。
以下是 explode 的定義(使用 C++11)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
const vector<string> explode(const string& s, const char& c)
{
string buff{""};
vector<string> v;
for(auto n:s)
{
if(n != c) buff+=n; else
if(n == c && buff != "") { v.push_back(buff); buff = ""; }
}
if(buff != "") v.push_back(buff);
return v;
}
|
上面的程式碼只是一個簡單的函式,但已經過各種情況的充分測試。以下是在 main 函式中的示例
1 2 3 4 5 6 7 8
|
int main()
{
string str{"the quick brown fox jumps over the lazy dog"};
vector<string> v{explode(str, ' ')};
for(auto n:v) cout << n << endl;
return 0;
}
|
將產生以下輸出
希望這篇短文能對您有所幫助。