类似于 C++ 中 java 的 string.split(" ") 的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16286095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:13:05  来源:igfitidea点击:

Similar function to java's string.split(" ") in C++

c++stringsplit

提问by

I am looking for the similar function in C++ to string.split(delimiter). It returns an array of strings cut by a specified delimiter.

我在 C++ 中寻找与string.split(delimiter). 它返回由指定分隔符切割的字符串数组。

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

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

采纳答案by dlscjs

You can use strtok. http://www.cplusplus.com/reference/cstring/strtok/

您可以使用 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;
}

回答by tbondwilkinson

I think this other stack overflow questions may answer this question:

我认为其他堆栈溢出问题可以回答这个问题:

Split a string in C++?

在 C++ 中拆分字符串?

In summary, there's no built-in method like with Java, but one of the users wrote this very similar method:

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

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

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