使用C ++进行strtok拆分时出错 [英] Error in strtok split using c++
问题描述
我必须使用C ++使用 strok
函数拆分示例字符串.样本字符串为:"This | is ||| a || sample || string |"
,而通常使用 strok
对其进行分割.
I have to split a sample string using strok
function using C++.
The sample string is: "This|is||a||sample||string|"
, while split this using strok
normally.
#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 |"
时,会得到预期的结果:
While changing the same string into "This| |a| |sample| |string|"
gives the expected result:
str:This
str:
str:a
str:
str:sample
str:
str:string
如何在不更改字符串的情况下获得预期结果?
How can I get the expect result without changing the string?
推荐答案
在 std :: string
上使用 std :: strtok
会产生不确定的行为,因为 std :: strtok
具有破坏性(提示: std :: string :: c_str()
返回 const char *
).
Using std::strtok
on std::string
will yield undefined behaviour, since std::strtok
is destructive (hint: std::string::c_str()
returns const char*
).
相反,请多次使用 std :: string :: find
和 std :: string :: substr
:
#include <iostream>
#include <string>
#include <iterator>
template <class OutputIt>
OutputIt safe_tokenizer(const std::string & s, char token, OutputIt out){
std::string::size_type pos = 0, f;
while((f = s.find(token, pos)) != std::string::npos){
*out++ = s.substr(pos, f - pos);
pos = f + 1;
}
if(pos < s.size())
*out++ = s.substr(pos);
return out;
}
int main(){
const std::string str = "Hello|World|How|Are|You";
safe_tokenizer(str, '|', std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
这篇关于使用C ++进行strtok拆分时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!