Splittig a string into multiple strings

This is a discussion on Splittig a string into multiple strings within the C Programming forums, part of the General Programming Boards category; Lets say I have input of "Oh my god I like pies" or something equally ridiculous, I'm having trouble getting ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    19

    Splittig a string into multiple strings

    Lets say I have input of "Oh my god I like pies" or something equally ridiculous, I'm having trouble getting this into multiple character arrays so that it's like...

    Array 1 is Oh
    Array 2 is my
    Array 3 is god
    Array 4 is I
    Array 5 is like
    Array 6 is pies

    I figured I could iterate through the string and everytime I noticed a space character... somehow switch to the next array and start filling... but... I have no idea how :-\

    Any help would be appreciated

    Cheers

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    strtok() is one option. You can look it up in your fav C reference yourself, but here's an example:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main() {
    	int i=1, n;
    	char string[]="The quick fox jumps over the lazy brown dog.";
    	char ray[16][32], *tok;
    	tok=strtok(string," ");  /* first instance */
    	strcpy(ray[0],tok);
    	while ((tok=strtok(NULL," "))!=NULL) { 
    		strcpy(ray[i],tok);
    		i++; 
    	}
    	/* now verify */
    	for (n=0; n<i; n++) printf("%s\n",ray[n]);
    	
    	return 0;
    }
    Two points to remember:
    • the first time pass a pointer to strtok, after that pass it NULL and it will progress thru the string originally indicated.
    • strtok will destroy the original string fed to it in the process


    [later] Maz's idea below is more elegant and optimizable but s/he's wrong about strtok, it's great for parsing input, etc, where the string is a local stack variable that's getting discarded anyway, so worth learning how to use properly (or don't bother and just consider it "awful"). Also, Maz's solution would be a waste of time on such a local variable; you'd have to make copies anyway. Apples, oranges, tomato...
    Last edited by MK27; 04-09-2009 at 10:57 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Maz
    Maz is offline
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    strtok is lousy function. Just go through the array, replacing space with \0 character, and store ptr to next char. Those stored ptrs will then work like arrays. (except the sizeof)

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    19
    Cheers, the strtok method worked really well for what I wanted :-)

    Really fast replies as well.

    Maz, I tried a method similar but it just completely failed. I got in a jumble with myself so started again.

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Maz's method would look something like this:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main() {
    	int i=1, n;
    	char string[]="The quick fox jumps over the lazy brown dog.";
    	char *ray[16], *tmp=string;
    	ray[0]=string;
    	while ((ray[i]=strchr(tmp,' '))!=NULL) {
    		ray[i][0]='\0';
    		ray[i]++; /*move pointer forward */
    		tmp=ray[i];  /* reassign tmp */
    		i++; 
    	}
    	/* now verify */
    	for (n=0; n<i; n++) printf("%s\n",ray[n]);
    	
    	return 0;
    }
    This also destroys "string", but it is much more efficient in that only one string function (strchr) is called per iteration, and strchr is probably less expensive than strtok or strcpy.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Maz
    Maz is offline
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    I was not thinking of using strchr, but something like


    Code:
    #define MAX_PIECES 10
    
    char foo[]="one lazy fox and so on";
    char *bar[MAX_PIECES];
    int index;
    bar[0]=foo;
    
    for(index=1;*foo!='\0';index++)
    {
        if(index==MAX_PIECES)
        {
             printf("OMG. More pieces that I can handle! %s:%d",__FILE__,__LINE__);
             exit(-1);
        }
        foo++;
        if(*foo==' ')
        {
            *foo='\0';
              bar[index]=foo+1;
        }
    }
    I did not test this, and this does not work when space is first or last char in array. These can be fixed by pondering this a bit more. Another issue is fixed size of bar array, but it can be handled by allocating the bar with malloc, and reallocing when necessary. (I do not know what are you going to use this for, so I did not use dynamic allocations which are somewhat slower).

    strtok is a pain in multithreaded applications, so for the sake of sanity, please use strtok_r() at least

  7. #7
    Maz
    Maz is offline
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    Oh, and I have also once written this Programmer's diary: C - Explode. but never tested it throughoutly, nor tried to optimize/improve it

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Good thinking. This would have to be the most highly optimization of all (without the strchr):
    Code:
    #include <stdio.h>
    
    int main() {
    	int i=1, n;
    	char string[]="The quick fox jumps over the lazy brown dog.";
    	char *ray[16], *tmp=string;
    	ray[0]=string;
    	while (*tmp!='\0') {
    		if (*tmp==' ') { *tmp='\0'; ray[i]=tmp+1; i++; }
    		tmp++; /*move pointer forward */
    	}
    	/* now verify */
    	for (n=0; n<i; n++) printf("%s\n",ray[n]);
    	
    	return 0;
    }
    which I did test it
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 02:40 AM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 10:03 PM
  3. Strings - char mystring[n] vs. string mystring
    By Diablo84 in forum C++ Programming
    Replies: 12
    Last Post: 04-06-2005, 05:54 PM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21