gpt4 book ai didi

c++ - 与 C++ 中 java 的 string.split (""类似的功能

转载 作者:IT老高 更新时间:2023-10-28 22:30:32 26 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c++ - 与 C++ 中 java 的 string.split (""类似的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16286095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com