c - srtok 在 c 中不工作

标签 c string strtok string-literals

这是我的代码,

#include <string.h>
#include <stdio.h>

main ()
{
    explode (" ", "this is a text");
}

    explode (char *delimiter, char string[])
{
char *pch;
printf ("Splitting string \"%s\" into tokens:\n",string);
pch = strtok (string,delimiter);
while (pch != NULL)
{
    printf ("%s\n",pch);
    pch = strtok (NULL, delimiter);
}
return 0;
}

我使用 gcc -o 1.exe 1.c 编译这段代码,没有显示任何错误。但是当我执行 1.exe 它显示 Splitting string "this is a text"into tokens: 并且在那一刻 1.exe 停止工作(窗口显示一个对话框)。任何人都可以告诉问题并解决问题吗?我正在使用 Windows 10。

最佳答案

虽然您不能使用 strtok 执行此操作,因为无法修改文字,但可以使用 strcspn 执行此操作。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void explode (char *delimiter, char *string);

int main()
{
    explode (" ", "this is a text");
    return 0;
}

void explode (char *delimiter, char *string)
{
    int span = 0;
    int offset = 0;
    int length = 0;

    if ( delimiter && string) {
        length = strlen ( string);
        printf ("Splitting string \"%s\" into tokens:\n",string);
        while (offset < length) {
            span = strcspn ( &string[offset],delimiter);//work from offset to find next delimiter
            printf ("%.*s\n",span, &string[offset]);//print span number of characters
            offset += span + 1;// increment offset by span and one characters
        }
    }
}

关于c - srtok 在 c 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902376/

相关文章:

c++ - c++ 的构造函数中的 const string &name 和 string name 之间的区别

c - 如何在文本文件中使用strtok

c - 我误解了 win32(也许还有 libc)strtok()

c - 我是否需要在 for 循环中使用 strcat 检查目标字符串长度

c - dev-c++ 套接字错误

c++ - 如何在构建时将 JSON 文件/对象包含在 C++ 中

c++ - 在 C++ 中使用字符串(搜索字符串、拆分字符串、cout<< 字符串)

javascript - 比较 Javascript 中的十进制字符串

C fgets strtok 和 atoi 读取 C 中的一行

c - 使用 malloc 函数创建的数组超出了所需的大小