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.
1 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #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
1 2 3 4 5 6 7 | 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.
Thank you so much. This helped.
Does this same function strtok() work in C++ too?