栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

话不多说,直接上代码

如果需要根据单一字符分割单词,直接用getline读取就好了,很简单

 #include 
 #include 
 #include 
 #include 
 using namespace std;
 
 int main()
 {
   string words;
   vector 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 
 #include 
 #include 
 #include 
 using namespace std;
 
 vector is_any_of(string str)
 {
   vector res;
   for (auto s : str)
     res.push_back(s);
   return res;
 }
 
 void split(vector& result, string str, vector 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 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++的时候有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/64214.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号