按字符串“malloc”分割不起作用并返回不同的分割
char str[2500] ="int *x = malloc(sizeof(int));";
const char s[9] = "malloc";
char *token = strtok(str, s);
while( token != NULL ) {
printf("%s\n", token );
token = strtok(NULL, s);
}
输出:
int *x =
(size
f(int));
我希望它返回:
int *x =
(sizeof(int));
但奇怪的是它拒绝这样做,而且我似乎无法弄清楚它为什么这样做。
编辑:我意识到尺寸太小,但仍然有问题。
char str[2500] ="int *x = malloc(sizeof(int));";
const char s[9] = "malloc";
char *token = strtok(str, s);
while( token != NULL ) {
printf("%s\n", token );
token = strtok(NULL, s);
}
Output:
int *x =
(size
f(int));
I want it to return:
int *x =
(sizeof(int));
but oddly it refuses to do that and I can't seem to figure out why it's doing that.
edit: I realized that the size is too small, but still has a problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
strtok
的第二个参数是用作分隔符的字符列表。它不是用作分隔符的完整字符串。所以你实际上拥有的是字符'm'
、'a'
、'l'
、'o'
> 和'c'
作为分隔符,因此这些字符之一出现的任何位置都会分割字符串。您想要的是使用
strstr
来搜索子字符串。然后,您可以使用它从str
的开头复制到子字符串的开头,然后再次从子字符串的末尾复制到str
的末尾。The second parameter to
strtok
is a list of characters which serve as delimiters. It is not a complete string used as a delimiter. So what you actually have is the characters'm'
,'a'
,'l'
,'o'
, and'c'
as delimiters, so anyplace one of those characters appears splits the string.What you want instead is to use
strstr
to search for a substring. Then you can use that to copy from the start ofstr
to the start of the substring, then copy again from the end of the substring to the end ofstr
.函数strtok的第二个参数表示字符串中存在的任何字符都可以用作终止字符。
因此,
一旦找到字符串“malloc”中存在的字符“o”,该子字符串就会终止。
您需要使用的是标准 C 字符串函数
strstr
。它将在源字符串中找到子字符串“mallpc”,您将能够输出“malloc”之前和之后的子字符串。例如
The second parameter of the function strtok means that any character present in the string can be used as a terminating character.
So this substring
is terminated as soon as the character 'o' present in the string "malloc" is found.
What you need to use is the standard C string function
strstr
. It will find the sub-string "mallpc" in the source string and you will be able to output the sub-strings before "malloc" and after it.For example