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

标签 c++ visual-c++

我有一个字符串“stack+overflow*newyork;”我必须拆分这个堆栈,溢出,纽约

有什么想法吗??

最佳答案

首先也是最重要的,如果可用的话,我总是会使用 boost::tokenizer 来完成这种任务(请参阅下面的好答案并点赞)

如果无法访问 boost,您有两种选择:

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

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

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);

关于c++ - 如何在vc++中拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1044088/

相关文章:

c++ - 在该命名空间中的另一个函数内向前声明一个命名空间中的函数

opencv - mat.at <short>(x,y)的访问冲突

c++ - 守护进程套接字在后台监听请求

c++ - MFC对话窗口不出现

c++ - 澄清 : Porting 32 to 64 bit

c++ - 使用指针从 char array[] 中移除/删除字符

dll - 如何在无需将exe与lib文件重新链接的情况下更新C++ dll?

当子类没有使用另一个宏时 C++ 宏失败

c++ - 如何在 C++ 中的两个类之间定义(重载)对称二元运算符,同时考虑 r 值?

c++ - 基于运算符推导模板返回类型? : result