C++怎么按字符分割字符串,返回数组

在python里有split函数,比如res_list ="aanbbncc".split("n")
那么res_list就是["aa","bb","cc"]
那么用c++是怎么实现这样的功能呢?有没有简洁高效的,我自己写的太烦锁了,感觉有点low,所以来求教各位大佬。
clipboard.png

阅读 5.3k
2 个回答

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。每次调用成功则返回被分割出片段的指针。

#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动态弱类型语言方便,但是优点还是有的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题