如何在vc ++中拆分字符串?

Cut*_*ute 1 c++ visual-c++

我有一个字符串"stack + ovrflow*newyork;" 我必须拆分这个堆栈,溢出,newyork

任何的想法??

Dou*_* T. 11

首先,如果可用的话,我总是会使用boost :: tokenizer来完成这种任务(请参阅下面的upvote)

如果没有增强功能,您可以选择以下几种方法:

您可以使用C++ std :: strings并使用stringstream和getline解析它们(最安全的方式)

std::string str = "stack+overflow*newyork;";
std::istringstream stream(str);
std::string tok1;
std::string tok2;
std::string tok3;

std::getline(stream, tok1, '+');
std::getline(stream, tok2, '*');
std::getline(stream, tok3, ';');

std::cout << tok1 << "," << tok2 << "," << tok3 << std::endl
Run Code Online (Sandbox Code Playgroud)

或者您可以使用strtok系列函数之一(请参阅Naveen对unicode不可知版本的回答;如果您对char指针感到满意,请参阅下面的xtofls评论以获取有关线程安全的警告)

char str[30]; 
strncpy(str, "stack+overflow*newyork;", 30);

// point to the delimeters
char* result1 = strtok(str, "+");
char* result2 = strtok(str, "*");
char* result3 = strtok(str, ";");

// replace these with commas
if (result1 != NULL)
{
   *result1 = ',';
}
if (result2 != NULL)
{
   *result2 = ',';
}

// output the result
printf(str);
Run Code Online (Sandbox Code Playgroud)


Edi*_*enz 6

提升标记器

很简单:

#include <boost/tokenizer.hpp>
#include <vector>
#include <string>
std::string stringToTokenize= "stack+ovrflow*newyork;";
boost::char_separator<char> sep("+*;");
boost::tokenizer< boost::char_separator<char> > tok(stringToTokenize, sep);
std::vector<std::string> vectorWithTokenizedStrings;
vectorWithTokenizedStrings.assign(tok.begin(), tok.end());
Run Code Online (Sandbox Code Playgroud)

现在,vectorWithTokenizedStrings具有您正在寻找的标记.注意boost :: char_separator变量.它保存令牌之间的分隔符.