c++如何分割字符串示例代碼
話不多說,直接上代碼
如果需要根據(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)容,大家學(xué)會了嗎?希望本文對大家使用C++的時(shí)候有所幫助。
相關(guān)文章
C語言中函數(shù)與指針的應(yīng)用總結(jié)
本篇文章是對C語言中函數(shù)與指針的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C++實(shí)現(xiàn)簡單校園導(dǎo)游系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡單校園導(dǎo)游系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03C++的靜態(tài)成員變量和靜態(tài)成員函數(shù)詳解
這篇文章主要為大家介紹了C++的靜態(tài)成員變量和靜態(tài)成員函數(shù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-12-12c語言根據(jù)用戶輸入的出生年份并計(jì)算出當(dāng)前年齡
這篇文章主要介紹了c語言根據(jù)用戶輸入的出生年份并計(jì)算出當(dāng)前年齡,需要的朋友可以參考下2023-03-03C++結(jié)構(gòu)體作為函數(shù)參數(shù)傳參的實(shí)例代碼
這篇文章主要介紹了C++結(jié)構(gòu)體作為函數(shù)參數(shù)傳參的實(shí)例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12