Tuesday, November 15, 2011

Splitting a String into Substrings in ANSI C

The easiest way to split a string into substrings is by the string.h library function strtok.

Here's an example on how to use it:
#include<stdio.h>
#include<string.h>

int main(void)
{
   char str[45] = "Bird!Bird!Bird!The bird is the word!";
   char *substr = NULL;
   /*"Initializes" strtok and gets the first substring*/
   substr = strtok(str," !");
   /*Loops until there are no more substrings*/
   while(substr!=NULL)
   {
       /*Prints the token*/
       puts(substr);
       /*Gets the next substrings*/
       substr = strtok(NULL," !");
   }
   puts("\nWhat remained from the primary string: ");
   puts(str);
   return 0;
}
/*Output:
Bird
Bird
Bird
The
bird
is
the
word

What remained from the primary string:
Bird
 */
The function can be a little odd to use, since it returns a pointer to a substring and not an array of strings like you would probably expect. When using it to split string, the following steps must be completed:

1)You must first "initialize" strtok by calling it using the string you want to split as the string primaryString. This will return a pointer to the first substring (which will be between your first character and the first delimiter character found)

2)To get the next substring, strtok must be called using the NULL pointer instead of the string you want to split. The function will return a pointer to a substring between the first delimiter found and the next delimiter character found (Note: the delimiter characters will not be included).

3)Using a loop you can get all the substrings from the string you want to split (you will still need to call strtok using a NULL pointer, so it will know that you have not changed the string you want to split).
When strtok will finish the splitting process it will return a NULL pointer.

PITFALL:It's very important to know that strtok replaces all delimiters with NULL, so your primary string will be destroyed after it's tokenized.


Question

References:
http://www.cplusplus.com/reference/cstring/

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger