c++如何分割字符串示例代碼
話不多說,直接上代碼
如果需要根據單一字符分割單詞,直接用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()) { //根據多個分割符分割 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++如何分割字符串示例代碼的全部內容,大家學會了嗎?希望本文對大家使用C++的時候有所幫助。
上一篇:C++編寫DLL動態(tài)鏈接庫的步驟與實現(xiàn)方法
欄 目:C語言
下一篇:VC++實現(xiàn)View內容保存為圖片的方法
本文標題:c++如何分割字符串示例代碼
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/2124.html
您可能感興趣的文章
- 04-02c語言沒有round函數(shù) round c語言
- 01-10如何判斷一個數(shù)是否為2的冪次方?若是,并判斷出來是多少次方
- 01-10深入理解C++中常見的關鍵字含義
- 01-10使用C++實現(xiàn)全排列算法的方法詳解
- 01-10如何判斷一個數(shù)是否為4的冪次方?若是,并判斷出來是多少次方
- 01-10如何查看進程實際的內存占用情況詳解
- 01-10c++中inline的用法分析
- 01-10如何尋找數(shù)組中的第二大數(shù)
- 01-10用C++實現(xiàn)DBSCAN聚類算法
- 01-10全排列算法的非遞歸實現(xiàn)與遞歸實現(xiàn)的方法(C++)


閱讀排行
本欄相關
- 04-02c語言函數(shù)調用后清空內存 c語言調用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調用函數(shù)求fibo C語言調用函數(shù)求
隨機閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實例總結
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文