Split String in C Programming

By | December 30, 2018

Let us learn how to Split String in C programming and how to implement STRTOK() function in C with its example, explanation, output and much more.

What is Strtok() function?

Strtok() in a built-in function in C programming library that helps in breaking down a series of words (a sentence) into multiple tokens or words.

Strtok() function is defined in string.h package. Here’s the syntax of strtok() function in C programming.

char *strtok(char *string, const char *delimiter)

where string represents the contents of the string which are to be broken down into multiple tokens,
and delimiter represents the delimiters on which the string tokenizing is dependent.

Must Read: C Program To Encrypt and Decrypt String Passwords

Note: This C program to split a string using strtok() function is compiled with GNU GCC compiler using Linux terminal on Linux Ubuntu operating system.

Split String in C Programming

#include<stdio.h>
#include<conio.h>
#include<string.h>
 
int main()
{
      int counter = 0,j = 0,k = 0;
      char temp[] = "Coding-Alpha";
      int limit = strlen(name);
      char arr[100][100];
      for(counter = 0, j = 0,k = 0; counter < limit;) 
      { 
          if((temp[counter] >= 'a' && temp[counter] <= 'z') || (temp[counter] >= 'A' && temp[counter] <= 'Z')) 
          {
                arr[j][k] = temp[counter];
                k++;
                counter++;
          }
          else
          {
                while(!isalpha(temp[counter])) 
                {
                      counter = counter + 1;
                }
                j = j + 1;
                k = 0;
          }
      }
      for(counter = 0; counter <= j; counter++) 
      {
             printf("%s\n", arr[counter]);
      }
      return 0;
}

Implementation of Strtok in C Programming

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

int main ()
{
      char temp[] ="Implementation of Strtok in C Programming";
      char * ptr;
      printf ("String splitted \"%s\" into multiple tokens:\n",str);
      ptr = strtok(temp," ,-");
      while (ptr != NULL)
      {
            printf ("%s\n", ptr);
            ptr = strtok(NULL, " ,-");
      }
      return 0;
}

Output

String splitted "Implementation of Strtok in C Programming" into multiple tokens:
Implementation
of 
Strtok
in
C
Programming

If you have any doubts about the implementation of Strtok function in C or how to split a string in C, let us know about it in the comment section. For more information on Strtok function, check TutorialsPoint.

One thought on “Split String in C Programming

Let's Discuss