C split char array into different variables

In C, how can I allocate a char array with a separator? or is it better to manipulate the string? what are some nice c char manipulation functions?

+5
source share
5 answers
#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;
}

You can watch this program. You must use strtok (input, ",") first. input is the string you want to use. Then you use strtok (NULL, ","). If the return value is true, you can print another group.

+10
source

Take a look at strtok () . strtok () is not a re-entry function.

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);
   }

, subtokens, :

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

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

- strtok

:

char name[20];
//pretend name is set to the value "My name"

split=strtok(name," ");

while(split != NULL)
{
    word=split;
    split=strtok(NULL," ");
}
+3

. , . :

void splitInput(int arr[], int sizeArr, char num[])
{
    for(int i = 0; i < sizeArr; i++)
        // We are subtracting 48 because the numbers in ASCII starts at 48.
        arr[i] = (int)num[i] - 48;
}
+2

You can simply replace the delimiter characters with NULL characters and save the address after the newly created NULL character in a new char * pointer:

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++;
}

Note that this code, of course, will not work if the input line contains more than 9 separator characters.

+1
source

All Articles