C split a char array into different variables


In C how can I separate a char array by a delimiter? Or is it better to manipulate a string? What are some good C char manipulation functions?

This question is tagged with c arrays string char

~ Asked on 2012-04-27 10:50:01

The Best Answer is


int main()
    char input[16] = "abc,d";
    char *p;
    p = strtok(input, ",");

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

           printf("%s\n", p);
    return 0;

you can look this program .First you should use the strtok(input, ",").input is the string you want to spilt.Then you use the strtok(NULL, ","). If the return value is true ,you can print the other group.

~ Answered on 2012-04-27 13:58:27


Look at strtok(). strtok() is not a re-entrant function.

strtok_r() is the re-entrant version of strtok(). Here's an example program from the manual:

   #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]);

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

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


Sample run which operates on subtokens which was obtained from the previous token based on a different delimiter:

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

1: hello:word:bye
 --> hello
 --> word
 --> bye
2: abc:def:ghi
 --> abc
 --> def
 --> ghi

~ Answered on 2012-04-27 10:51:37

Most Viewed Questions: