国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

c++如何分割字符串示例代碼

2020-01-26 14:28:41
字體:
來源:轉載
供稿:網友

話不多說,直接上代碼

如果需要根據單一字符分割單詞,直接用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的函數了:

 #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++的時候有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广宁县| 日喀则市| 秦皇岛市| 巴楚县| 木里| 漳平市| 西乌珠穆沁旗| 囊谦县| 富平县| 湖南省| 汾西县| 邵阳市| 天津市| 应城市| 唐海县| 沧源| 乡宁县| 读书| 修武县| 渝中区| 遵化市| 水城县| 乌兰县| 濮阳县| 南投县| 定西市| 三穗县| 淮南市| 台湾省| 北碚区| 同心县| 娱乐| 宁河县| 延寿县| 广元市| 区。| 胶南市| 濉溪县| 香格里拉县| 抚松县| 侯马市|