c++如何分割字符串示例代碼
更新時間:2016年08月10日 10:20:53 投稿:daisy
因為c++字符串沒有split函數(shù),所以字符串分割單詞的時候必須自己手寫,也相當于自己實現(xiàn)一個split函數(shù)吧!下面跟小編一起來看看如何實現(xiàn)這個功能。
話不多說,直接上代碼
如果需要根據(jù)單一字符分割單詞,直接用getline讀取就好了,很簡單
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string words;
vector<string> results;
getline(cin, words);
istringstream ss(words);
while (!ss.eof())
{
string word;
getline(ss, word, ',');
results.push_back(word);
}
for (auto item : results)
{
cout << item << " ";
}
}
如果是多種字符分割,比如,。!等等,就需要自己寫一個類似于split的函數(shù)了:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
vector<char> is_any_of(string str)
{
vector<char> res;
for (auto s : str)
res.push_back(s);
return res;
}
void split(vector<string>& result, string str, vector<char> delimiters)
{
result.clear();
auto start = 0;
while (start < str.size())
{
//根據(jù)多個分割符分割
auto itRes = str.find(delimiters[0], start);
for (int i = 1; i < delimiters.size(); ++i)
{
auto it = str.find(delimiters[i],start);
if (it < itRes)
itRes = it;
}
if (itRes == string::npos)
{
result.push_back(str.substr(start, str.size() - start));
break;
}
result.push_back(str.substr(start, itRes - start));
start = itRes;
++start;
}
}
int main()
{
string words;
vector<string> result;
getline(cin, words);
split(result, words, is_any_of(", .?!"));
for (auto item : result)
{
cout << item << ' ';
}
}
例如:輸入hello world!Welcome to my blog,thank you!

以上就是c++如何分割字符串示例代碼的全部內(nèi)容,大家學會了嗎?希望本文對大家使用C++的時候有所幫助。
相關文章
C++類與對象深入之引用與內(nèi)聯(lián)函數(shù)與auto關鍵字及for循環(huán)詳解
朋友們好,這篇播客我們繼續(xù)C++的初階學習,現(xiàn)在對一些C++的入門知識做了些總結,整理出來一篇博客供我們一起復習和學習,如果文章中有理解不當?shù)牡胤?還希望朋友們在評論區(qū)指出,我們相互學習,共同進步2022-06-06

