c++ - 用 strtok 拆分后大部分字符串消失了吗?

标签 c++ string token strtok

e: 谢谢大家,没想到strtok实际上修改了字符串本身。希望我以后不那么傻。

我最近开始通过一本书学习 C++。我现在正在阅读有关解析字符串的章节。

我的下一个任务是在用 strtok 拆分后将字符串的标记放回原处,但我不明白第一个定界符后字符串的其余部分去了哪里!请记住,我对此很陌生,如果这是一个愚蠢的问题,我深表歉意。

基本上发生的事情是这样的: 1. 我输入一个字符串“嘿,你好吗?” 2、打印出来,正常。 3.然后我把它分成标记(使用定界符和空格) 4.它们都打印整齐 5. 再次打印字符串,剩下的就是“嘿”。

那么如何取回字符串的其余部分呢?

这是我的代码:

char the_string[ 81], *p;

cout << the_string << endl;

cout << "Input a string to parse: ";
cin.getline(the_string, 81);
p = strtok(the_string, ", ");
while (p != NULL) {
  cout << p << endl;
  p = strtok(NULL, ", ");
} 

cout << the_string << endl;

最佳答案

strtok()修改它操作的字符串:

If str != NULL, the function searches for the first character which is not separator. This character is the beginning of the token. Then the function searches for the first separator character. This character is the end of the token. Function terminates and returns NULL if end of str is encountered before end of the token is found. Otherwise, a pointer to end of the token is saved in a static location for subsequent invocations. This character is then replaced by a NULL-character and the function returns a pointer to the beginning of the token.

在传递给 strtok() 之前复制字符串。

在 C++ 中有更好的方法来实现这一点,但由于这听起来像是家庭作业,因此您可能不允许使用它们。

关于c++ - 用 strtok 拆分后大部分字符串消失了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11957901/

相关文章:

c++ - 获取Openssl证书错误中的错误字符串

c++ - 我可以制作 C++ 对象的按位拷贝吗?

java - 编译时常量在 Switch Case Java 中的使用

c - C 上的字符串行为

c - ‘;’ token 之前出现错误 : expected ‘,’ , ‘)’ 或 ‘.’

c++ - 无法使用 PhotoViewer.dll 执行 CreateProcess

c++ - pthread_setschedprio() 失败并显示 "EINVAL"

c - 在 C 中提取字符串模式(无库)

c - C语言中去除字符串中的空格

angular - 如何从 jwt token 获取用户角色