OneBite.Dev - Coding blog in a bite size

split a string in C

Code snippet on how to split a string in C

  #include<stdio.h> 
  #include<string.h>
  int main()
  {
    char str[100] = "Hello, World!";
    char *token = strtok(str, ",");
    while (token != NULL) 
    {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }
    return 0;
}

This code is an example of splitting a string in C. It starts off by including the two necessary libraries (stdio.h, string.h). Then, a string is declared with the content “Hello, World!“. We then use strtok() to split the string into tokens based on the ”,” character, and assign the resulting token to a pointer to a string. A loop is then created that iterates through each token as it’s printed to the console until the token is null. Finally, the program returns 0. In other words, this program could be used to split the string “Hello, World!” into two separate strings, “Hello” and ” World!” with the comma being used as the delimiter.

c