c++如何分割字串範例程式碼_C 語言

來源:互聯網
上載者:User

話不多說,直接上代碼

如果需要根據單一字元分割單詞,直接用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++的時候有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.