The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
strtok() is one of the inbuilt string function in c programming which is used to split the given string with the given character.
The following diagram clearly illustrate the working principle of strtok() inbuilt string function 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.
strtok(str, chr);
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.
#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
The above program illustrate that strtok() function is used to split the string into parts by comma delimitting characters.
Let us split the string by using comma delimitting character without using strtok() inbuilt string function.
#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
The above program looks verbose but yields same the result. Modify a delimiter to see a change.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019