C将char数组拆分为不同的变量

Dan*_*ore 11 c arrays string char

在C中如何用分隔符分隔char数组?或者操纵字符串更好?有什么好的C char操作函数?

Hon*_*Wei 15

#include<string.h>
#include<stdio.h>
int main()
{
    char input[16] = "abc,d";
    char *p;
    p = strtok(input, ",");

    if(p)
    {
    printf("%s\n", p);
    }
    p = strtok(NULL, ",");

    if(p)
           printf("%s\n", p);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你可以查看这个程序.首先你应该使用strtok(输入,",").输入是你想要spilt的字符串.然后你使用strtok(NULL,",").如果返回值为true,则可以打印另一个组.

  • 谢谢您提供的代码,对不起,愚蠢的问题,您为什么第二次使用strtok?另外,“如果返回值为true,则可以打印另一个组”。意思? (2认同)

P.P*_*.P. 12

看看strtok().strtok()不是可重入函数.

strtok_r()是strtok()的可重入版本.以下是手册中的示例程序:

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

   int main(int argc, char *argv[])
   {
       char *str1, *str2, *token, *subtoken;
       char *saveptr1, *saveptr2;
       int j;

       if (argc != 4) {
           fprintf(stderr, "Usage: %s string delim subdelim\n",argv[0]);
           exit(EXIT_FAILURE);
       }

       for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
           token = strtok_r(str1, argv[2], &saveptr1);
           if (token == NULL)
               break;
           printf("%d: %s\n", j, token);

           for (str2 = token; ; str2 = NULL) {
               subtoken = strtok_r(str2, argv[3], &saveptr2);
               if (subtoken == NULL)
                   break;
               printf(" --> %s\n", subtoken);
           }
       }

       exit(EXIT_SUCCESS);
   }
Run Code Online (Sandbox Code Playgroud)

对基于不同分隔符从前一个令牌获得的子字符进行操作的样本运行:

$ ./a.out hello:word:bye=abc:def:ghi = :

1: hello:word:bye
 --> hello
 --> word
 --> bye
2: abc:def:ghi
 --> abc
 --> def
 --> ghi
Run Code Online (Sandbox Code Playgroud)


And*_*rew 6

一种选择是 strtok

例子:

char name[20];
//pretend name is set to the value "My name"
Run Code Online (Sandbox Code Playgroud)

您想在两个单词之间的空格处将其分开

split=strtok(name," ");

while(split != NULL)
{
    word=split;
    split=strtok(NULL," ");
}
Run Code Online (Sandbox Code Playgroud)


mic*_*c_e 5

您可以简单地将分隔符替换为 NULL 字符,并将新创建的 NULL 字符后面的地址存储在新的 char* 指针中:

char* input = "asdf|qwer"
char* parts[10];
int partcount = 0;

parts[partcount++] = input;

char* ptr = input;
while(*ptr) { //check if the string is over
    if(*ptr == '|') {
        *ptr = 0;
        parts[partcount++] = ptr + 1;
    }
    ptr++;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果输入字符串包含超过 9 个分隔符,则此代码当然不起作用。