c - 在 C 不同变量中分割字符串

标签 c strtok strcpy

我有一个像这样的字符串:

char string = " dog beans 1234 cat rice 0123 bird peanut 7777"

我想将其拆分为不同的变量,例如:

char animals[1000], food[1000], numbers[1000];

到目前为止我做了什么:

int i;
while (string != NULL)  {
    for (i = 0, i < 1000, i++) {
        strcpy(animals[i], strtok(string, " ");
        strcpy(food[i], strtok(string, " ");
        strcpy(numbers[i], strtok(string, " ");
    }
}

第一个循环工作正常,但第二个循环抛出段错误。

最佳答案

首先,您将 animalsfoodnumbers 视为字符串数组,但将它们声明为字符数组。您需要将它们声明为 char 数组的数组,或 char 指针的数组,在这种情况下,您需要使用 malloc 分配字符串>.

char animals[100][20];
char food[100][20];
char numbers[100][20];

其次,当您使用相同的非空初始参数调用 strtok 时,您将获得相同的值。您需要在第一个调用之后的所有调用中传递 NULL:

strcpy(animals[i], strtok(string, " "));
strcpy(food[i], strtok(NULL, " "));
strcpy(numbers[i], strtok(NULL, " "));

关于c - 在 C 不同变量中分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42321658/

相关文章:

c - printf 返回什么?

c - 大小 1 的无效读取

c++ - strtok 字符串并修改 token 值

c++ - 'strcpy' : cannot convert parameter 2 from 'WCHAR *' to 'const char *

c - 字符串解析,纯C

c - rand() 每次给出几乎相同的数字

条件变量 - 意外行为

c - 从 C 中的矩阵中删除分号

crash - linux 上的 jvmti 代理 fatal error : C [libc. so.6+0x7ae68] strcpy+0x18

c - 警告 : incompatible implicit declaration of built-in function 'strlen' and 'strcpy'