与Java的string.split(“”)类似的函数,在C ++中[重复]

问题描述 投票:15回答:2

此问题已经在这里有了答案:

我正在寻找C ++中与string.split(delimiter)类似的功能。它返回由指定的定界符剪切的字符串数组。

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

c++ string split
2个回答
4
投票

您可以使用strtok。http://www.cplusplus.com/reference/cstring/strtok/

#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
std::vector<std::string> split(std::string str,std::string sep){
    char* cstr=const_cast<char*>(str.c_str());
    char* current;
    std::vector<std::string> arr;
    current=strtok(cstr,sep.c_str());
    while(current!=NULL){
        arr.push_back(current);
        current=strtok(NULL,sep.c_str());
    }
    return arr;
}
int main(){
    std::vector<std::string> arr;
    arr=split("This--is--split","--");
    for(size_t i=0;i<arr.size();i++)
        printf("%s\n",arr[i].c_str());
    return 0;
}

1
投票

我认为其他堆栈溢出问题可能会回答以下问题:

Split a string in C++?

总之,没有像Java这样的内置方法,但是其中一位用户编写了这种非常相似的方法:

https://stackoverflow.com/a/236803/1739039

© www.soinside.com 2019 - 2024. All rights reserved.