For example, you have a string sentence “CSEstack is a programming portal”. You want to get each word from the sentence like “CSEstack”, “is”, “a”, “programming” and “portal.”. This can be done by splitting the sentence and storing them.
You can use function strtok_r() to split the sentence in C/C++ programming.
Input parameter to the strtok_r() function:
How does it work?
strtok_r()
returns the token pointing to the next substring after delimiter. Calling function strtok_r()
in a loop will give us all the sub-strings after splitting.
Check the below program.
// C program to demonstrate working of strtok_r() // by splitting string based on space character. #include <stdio.h> #include <string.h> int main() { char strToSplit[] = "CSEstack is a programming portal"; char *token; int i=0; char *strArr[5] = {0}; char* strSplit = strToSplit; while ((token = strtok_r(strSplit , " ", &strSplit))) strArr[i++] = token; for(int i=0; i<5; i++) printf("\n ++i) %s",strArr[i]); }
In the above program, the delimiter is space ” “. So, The string between two spaces will be considered as one token.
Output:
1) CSEstack 2) is 3) a 4) programming 5) portal
After splitting the string, you can also store the data in the array.
Use Cases:
CSV (comma separated value) is a special type of data structure where we can save the different data entities separated by a comma.
Example:
Name,Age,profession Steve,34,developer Noob,55,tester Clave,32,designer
You can simply read the CSV file and loop over each line to get the name, age and profession of the employee by using strtok_r()
. Here, delimiter will be ‘,’ instead of space.
// C program to demonstrate working of strtok_r() // by splitting string based on space character. #include <stdio.h> #include <string.h> int main() { char strEmpData[] = "Steve,34,developer"; char *token; int i=0; char *strArr[3] = {0}; char* strSplit = strEmpData; while ((token = strtok_r(strSplit , ",", &strSplit))) strArr[i++] = token; printf("\n Name: %s",strArr[0]); printf("\n Age: %d",atoi(strArr[1])); printf("\n Profession: %s",strArr[2]); }
Output:
Name: Steve Age: 34 Profession: developer
Related String Program in C:
Any question or point to discuss this code to split String in C programming, write in the comment section.