OneBite.Dev - Coding blog in a bite size

convert a string to an array in C

Code snippet on how to convert a string to an array in C

  #include <string.h>
  #include <stdio.h>
  #include <stdlib.h>
  
  int main()
  {
     char source[100] = "Hello World!";
     char *token;
     const char s[2] = " ";

     token = strtok(source, s);

     while(token != NULL)
     {
        printf("%s\n", token);
        token = strtok(NULL, s);
     }
     return 0;
  }

This code starts by including three header files: string.h, stdio.h, and stdlib.h. It then creates a string called source, that contains the text “Hello World!” and two constants; a string s containing ” ” (a single space), and an integer main. The main function is used to control the execution of the program.

The strtok function is then used to split the string source into tokens (or smaller strings), separated by a single space. To do this, it uses the first constant, s (the space), as the delimiter. The function then returns the first token in the string source, which is “Hello”. This is then printed to the console using printf.

The strtok function is then called again by passing it a NULL argument, rather than the string source. This causes it to pick up from where it left off, and return the next token in the string. This process continues until it reaches the end of the string, at which point the token pointer is set to NULL and the program terminates.

c