/* SplittingAtoms.c (c) Kari Laitinen http://www.naturalprogramming.com/ 2013-11-25 File created. 2013-11-25 Last modification. This program shows, among other things, how to split a longer string into substrings (tokens) with the strtok() function. Note that strtok() modifies the string that is given as the first parameter to it. It seems that strtok() does not return empty strings. */ #include #include int main() { char atomic_text[] = "\n Atoms consist of protons, neutrons\n and electrons." ; printf( "%s\n", atomic_text ) ; char substrings_from_text [ 10 ] [ 80 ] ; // Now we'll split the atomic text in those places where there is // a newline \n or a comma. char* found_substring = strtok( atomic_text, "\n," ) ; int substring_index = 0 ; while ( found_substring != NULL ) { strcpy( substrings_from_text[ substring_index ], found_substring ) ; substring_index ++ ; found_substring = strtok( NULL, "\n," ) ; } int number_of_found_substrings = substring_index ; for ( substring_index = 0 ; substring_index < number_of_found_substrings ; substring_index ++ ) { printf( "\n%d:%s", substring_index, substrings_from_text[ substring_index ] ) ; } strcpy( atomic_text, "" ) ; for ( substring_index = 0 ; substring_index < number_of_found_substrings ; substring_index ++ ) { strcat( atomic_text, substrings_from_text[ substring_index ] ) ; } printf( "\n\n%s\n", atomic_text ) ; // We'll split the rejoined strings in those places where // there is a space character. found_substring = strtok( atomic_text, " " ) ; substring_index = 0 ; while ( found_substring != NULL ) { strcpy( substrings_from_text[ substring_index ], found_substring ) ; substring_index ++ ; found_substring = strtok( NULL, " " ) ; } number_of_found_substrings = substring_index ; for ( substring_index = 0 ; substring_index < number_of_found_substrings ; substring_index ++ ) { printf( "\n%d:%s", substring_index, substrings_from_text[ substring_index ] ) ; } printf( "\n" ) ; } /* The output of this program is: Atoms consist of protons, neutrons and electrons. 0: Atoms consist of protons 1: neutrons 2: and electrons. Atoms consist of protons neutrons and electrons. 0:Atoms 1:consist 2:of 3:protons 4:neutrons 5:and 6:electrons. */