欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時間:2020-01-10|欄目: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

網頁制作CMS教程網絡編程軟件編程腳本語言數(shù)據庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網 版權所有