在python里有split函数,比如res_list ="aanbbncc".split("n")
那么res_list就是["aa","bb","cc"]
那么用c++是怎么实现这样的功能呢?有没有简洁高效的,我自己写的太烦锁了,感觉有点low,所以来求教各位大佬。
在python里有split函数,比如res_list ="aanbbncc".split("n")
那么res_list就是["aa","bb","cc"]
那么用c++是怎么实现这样的功能呢?有没有简洁高效的,我自己写的太烦锁了,感觉有点low,所以来求教各位大佬。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string a, string b){
vector<string> result;
std::string::size_type i = 0;
std::string::size_type found = a.find(b);
while (found != std::string::npos){
result.push_back(a.substr(i, found - i));
i = found + b.size();
found = a.find(b, i);
}
result.push_back(a.substr(i, a.size() - i));
return result;
}
int main()
{
string a = "aa\nbb\ncc";
vector<string> result = split(a, "\n");
for(int i=0;i<result.size();i++)
cout<<result[i]<<endl;
return 0;
}
自己写个函数也不是很复杂啊,c++是静态强类型语言,肯定没有python动态弱类型语言方便,但是优点还是有的
3 回答2.1k 阅读✓ 已解决
4 回答4.5k 阅读✓ 已解决
2 回答3.6k 阅读✓ 已解决
4 回答3.9k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答576 阅读✓ 已解决
1 回答4.6k 阅读✓ 已解决
1、通过stl实现
涉及到string类的两个函数find和substr:
1、find函数
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出现的位置。
参数说明:str为子字符串,pos为初始查找位置。
返回值:找到的话返回第一次出现的位置,否则返回string::npos
2、substr函数
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:获得子字符串。
参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
返回值:子字符串
2、通过使用strtok()函数实现
原型:char strtok(char str, const char *delim);
功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
描述:strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时 则会将该字符改为0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。