strtok(): parse string into tokens

#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

If no more tokens are found then we get NULL as output of strtok(). We will use this to loop through and display all tokens.
#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

Example 1: Splitting a String Using Space as a Delimiter

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
---

Example 2: Splitting a String with Multiple Delimiters

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
---

Example 3: Tokenizing with User Input

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!


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com






    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer