按字符串“malloc”分割不起作用并返回不同的分割

发布于 2025-01-12 15:37:42 字数 432 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一片旧的回忆 2025-01-19 15:37:42

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 of str to the start of the substring, then copy again from the end of the substring to the end of str.

梦里°也失望 2025-01-19 15:37:42

函数strtok的第二个参数表示字符串中存在的任何字符都可以用作终止字符。

因此,

(sizeof(int))

一旦找到字符串“malloc”中存在的字符“o”,该子字符串就会终止。

您需要使用的是标准 C 字符串函数 strstr。它将在源字符串中找到子字符串“mallpc”,您将能够输出“malloc”之前和之后的子字符串。

例如

char str[2500] ="int *x = malloc(sizeof(int));";
    const char s[9] = "malloc";
    char *p = strstr(str, s);

    if ( p != NULL )
    {
        printf( "%.*s\n", ( int )( p - str ), str );
        if ( p[strlen( s )] != '\0' ) puts( p );
    }

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

(sizeof(int))

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

char str[2500] ="int *x = malloc(sizeof(int));";
    const char s[9] = "malloc";
    char *p = strstr(str, s);

    if ( p != NULL )
    {
        printf( "%.*s\n", ( int )( p - str ), str );
        if ( p[strlen( s )] != '\0' ) puts( p );
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文