【发布时间】:2013-10-26 10:42:52
【问题描述】:
我必须使用 C++ 使用 strok 函数拆分示例字符串。
示例字符串是:"This|is||a||sample||string|",而通常使用strok 拆分它。
#include <stdio.h>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string str="This||a||sample||string|";
string a;
str=strtok ((char *)str.c_str(),"|");
while (str.c_str() != NULL)
{
printf ("str:%s\n",str.c_str());
str = strtok (NULL, "|");
}
return 0;
}
结果:
str:This
str:a
str:sample
str:string
将相同的字符串更改为"This| |a| |sample| |string|" 会得到预期的结果:
str:This
str:
str:a
str:
str:sample
str:
str:string
如何在不更改字符串的情况下获得预期结果?
【问题讨论】:
-
根据ideone,您的示例会导致运行时错误。你确定你发布了正确的代码吗?
str=strtok ((char *)str.c_str(),"|");对我来说有点奇怪.. -
int main() { char str[]="This| |a| |sample| |string|";字符 *ptr; ptr=strtok ((char *)str,"|"); while (ptr != NULL) { printf ("str:%s\n",ptr); ptr = strtok (NULL, "|"); } 返回 0; } 使用此代码
-
您可以使用问题正下方的编辑按钮
edit您的问题。我建议你在那里添加你的代码。 -
请注意 c_str 是一个
const值。你不应该以你的方式操纵它。您是否尝试将其复制到char缓冲区(或尝试搜索可以拆分std::string的方法)?
标签: c++