#include <stdio.h>
#include <string.h>
int main ()
{
char str[50] ="Welcome-to-plus2net";
char *p;
p = strtok (str,"-");
printf ("%s\n",p);
}
Output is here
Welcome
Output of strtok() gives us a pointer to the first token. To get the subsequent tokens we have to use NULL in place of the main string.
We can parse a string into sequence of tokens by using strtok()
string function.
strtok(main_string, delimiter_string);
#include <stdio.h>
#include <string.h>
int main ()
{
char str[50] ="Welcome-to-plus2net";
char *p;
p = strtok (str,"-");
printf ("%s\n",p); // Welcome
p = strtok(NULL,"-");
printf ("%s\n",p); // to
}
Output is here
Welcome
to
Note : In the second call to strtok() we have not used the original string, we used NULL
#include <stdio.h>
#include <string.h>
int main ()
{
char str[50] ="Welcome-to-plus2net";
char *p;
p = strtok (str,"-");
while( p != NULL ) {
printf( " %s\n", p );
p = strtok(NULL, "-");
}
}
Output is here
Welcome
to
plus2net
This example demonstrates how to split a string into individual words using spaces as delimiters.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "plus2net provides great tutorials";
char *token = strtok(str, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
Output:
plus2net
provides
great
tutorials
---
Use multiple delimiters such as commas, spaces, and periods to split a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "apple, banana, orange. grape";
char *token = strtok(str, ",. ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",. ");
}
return 0;
}
Output:
apple
banana
orange
grape
---
This example allows the user to enter a string and choose a delimiter to split it.
#include <stdio.h>
#include <string.h>
int main() {
char str[100], delim[10];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a delimiter: ");
scanf("%s", delim);
char *token = strtok(str, delim);
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, delim);
}
return 0;
}
Output:
Enter a string: Hello, World!
Enter a delimiter: ,
Hello
World!