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

首頁(yè) > 編程 > C++ > 正文

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

2020-05-23 14:01:10
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

話不多說(shuō),直接上代碼

如果需要根據(jù)單一字符分割單詞,直接用getline讀取就好了,很簡(jiǎn)單

 #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 << " ";   } }

如果是多種字符分割,比如,。!等等,就需要自己寫(xiě)一個(gè)類似于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ù)多個(gè)分割符分割     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,字符串分割函數(shù),split,字符串分割,c語(yǔ)言分割字符串

以上就是c++如何分割字符串示例代碼的全部?jī)?nèi)容,大家學(xué)會(huì)了嗎?希望本文對(duì)大家使用C++的時(shí)候有所幫助。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 赤峰市| 双牌县| 衡阳县| 渑池县| 屯留县| 蓝田县| 云浮市| 江孜县| 泗阳县| 许昌县| 大城县| 绵阳市| 秦皇岛市| 西昌市| 施秉县| 恭城| 靖西县| 郯城县| 松滋市| 公安县| 图们市| 东平县| 乌拉特前旗| 图木舒克市| 翁牛特旗| 深圳市| 洛隆县| 朔州市| 武安市| 连云港市| 项城市| 岳阳县| 鄂尔多斯市| 留坝县| 上林县| 樟树市| 巴南区| 外汇| 天气| 东平县| 新野县|