The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

strtok() In C

Purpose of strtok()

strtok() is one of the inbuilt string function in c programming which is used to split the given string with the given character.

How strtok() Works

The following diagram clearly illustrate the working principle of strtok() inbuilt string function in c.

strtok() in c

In the above diagram, strtok() will split the string str into parts, wherever the given character is present in the string. Splitting is done by replacing a user mentioned delimitting character with '\0' i.e) Null character.

Syntax - strtok()

  • strtok() accepts two parameters,
  • First parameter must be a string and second parameter must be a character.
  • Second parameter must be a delimitting characters like , : ;
  • To use strtok() inbuilt string functions in C, we need to declare #include<string.h> header file.
Syntax
strtok(str, chr);

C Program - strtok()

Let us work through strtok() function, In the following program we will split the string by using comma delimitting character with the help of strtok() inbuilt string function.

c-using-strtok.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[30]="s, t, r, t, o, k, w, o, r, k, s";
char chr[] = ",";
char *tok;
tok = strtok(str, chr);
while(tok!=NULL)
{
printf(" %s\n", tok);
tok = strtok(NULL,chr);
}
return 0;
}
s
t
r
t
o
k
w
o
r
k
s

Note:

The above program illustrate that strtok() function is used to split the string into parts by comma delimitting characters.

C Program - Without strtok()

Let us split the string by using comma delimitting character without using strtok() inbuilt string function.

c-without-strtok.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[30] = "s, t, r, t, o, k, w, o, r, k, s";
char chr[] = ",", i, j;
for(i=0; str[i]!='\0'; i++)
{
if(str[i] == chr[0])
str[i]='\0';
}
for(j=0; j<i; j++)
if(str[j] != '\0')
printf("%c",str[j]);
else
printf("\n");
return 0;
}
s
t
r
t
o
k
w
o
r
k
s

Note:

The above program looks verbose but yields same the result. Modify a delimiter to see a change.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report