C program to print string tokens

CServer Side ProgrammingProgramming

Suppose we have a string s that contains a sentence with few words. We shall have to print each word into new lines. To do this we can use the strtok() function under the string.h header file. This function takes the string and a delimiter. Here the delimiter is blank space " ".

So, if the input is like s = "Let us see some string tokenizing fun", then the output will be

Let
us
see
some
string
tokenizing
fun

To solve this, we will follow these steps −

  • token := first word by using strtok(s, " ") here delimiter is " "

  • while token is non-zero, do:

    • display token

    • token := next token of s, from now pass NULL as first argument of strtok with same delimiter space " ".

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
#include <string.h>
int main(){
    char s[] = "Let us see some string tokenizing fun";
    char* token = strtok(s, " ");
    while (token) {
        printf("%s\n", token);
        token = strtok(NULL, " ");
    }
}

Input

Let us see some string tokenizing fun

Output

Let
us
see
some
string
tokenizing
fun
raja
Published on 08-Oct-2021 11:15:09
Advertisements