手机
当前位置:查字典教程网 >编程开发 >C语言 >c++如何分割字符串示例代码
c++如何分割字符串示例代码
摘要:话不多说,直接上代码如果需要根据单一字符分割单词,直接用getline读取就好了,很简单#include#include#include#i...

话不多说,直接上代码

如果需要根据单一字符分割单词,直接用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++如何分割字符串示例代码1

以上就是c++如何分割字符串示例代码的全部内容,大家学会了吗?希望本文对大家使用C++的时候有所帮助。

【c++如何分割字符串示例代码】相关文章:

如何在TC2.0中调用汇编程序

C++输出斐波那契数列的两种实现方法

C实现分子沉积模拟的示例代码

最长公共子字符串的使用分析

用c语言根据可变参数合成字符串的实现代码

C语言小程序 杨辉三角示例代码

c语言中if 语句的作用范围示例代码

VC6.0如何创建以及调用动态链接库实例详解

c语言中用字符串数组显示菜单的解决方法

C++ 十进制转换为二进制的实例代码

精品推荐
分类导航