![]() |
VOOZH | about |
In this article, we will learn how to split a string into a number of sub-strings using the C program.
The most straightforward method to split a string into substrings using a delimiter is by using strtok() function. Let’s take a look at an example:
Geeks for Geeks
Explanation: strtok() splits the string into substrings using a comma as the delimiter. It modifies the original string in-place and returns each token (substring) one by one until there are no more tokens left.
There are also a few other methods in C on how to split a string into a number of sub-strings. Some of them are as follows:
Manually traverse the string, copying each substring into a temporary string whenever we encounter a delimiter. This method doesn't modify the original string and allows more control over how the substrings are stored.
Geeks for Geeks
Replace delimiter by null character '\0' and print the substring till this null character. After that, move pointer after this null character and print the substring till next null character. Keep doing this till the end of the string.
Geeks for Geeks