strtok() splits a modifiable C string into tokens using one or more delimiter characters. The first call receives the string; later calls pass NULL to continue from the previous position.
char *token = strtok(string, delimiters);
token = strtok(NULL, delimiters);
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "Welcome-to-plus2net";
char *token = strtok(text, "-");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, "-");
}
return 0;
}
Output
Welcome
to
plus2net
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "apple, banana, orange. grape";
char *token = strtok(text, ",. ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",. ");
}
return 0;
}
Output
apple
banana
orange
grape
#include <stdio.h>
#include <string.h>
int main(void) {
char text[100];
char delimiters[20];
printf("Enter a string: ");
if (fgets(text, sizeof(text), stdin) == NULL) {
return 1;
}
printf("Enter delimiter characters: ");
if (fgets(delimiters, sizeof(delimiters), stdin) == NULL) {
return 1;
}
delimiters[strcspn(delimiters, "\n")] = '\0';
char *token = strtok(text, delimiters);
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, delimiters);
}
return 0;
}
strtok() writes null characters into the input array to terminate each token. Use a writable character array, not a string literal, and make a copy first if the original text must be preserved.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.