雷火电竞-中国电竞赛事及体育赛事平台

歡迎來(lái)到入門教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

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

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

話不多說(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 << " ";
   }
 }

如果是多種字符分割,比如,。!等等,就需要自己寫一個(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++如何分割字符串示例代碼的全部?jī)?nèi)容,大家學(xué)會(huì)了嗎?希望本文對(duì)大家使用C++的時(shí)候有所幫助。

上一篇:C++編寫DLL動(dòng)態(tài)鏈接庫(kù)的步驟與實(shí)現(xiàn)方法

欄    目:C語(yǔ)言

下一篇:VC++實(shí)現(xiàn)View內(nèi)容保存為圖片的方法

本文標(biāo)題:c++如何分割字符串示例代碼

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/2124.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

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

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有