Link to home
Start Free TrialLog in
Avatar of xilgaro
xilgaro

asked on

splitting a string in two parts

Hi, all:
  I have a string with spaces. I'd like to split the string in two parts, in the first part I want one of the word of the string, let's say the third, and in the other part I want the rest.
  I mean:

String= "first two three fourth fifth"
String_1= "three"
String_2= "first two fourth fifth"

In principle I don't know the number of words in the string, I only know the position of the word I want.

I know it should be easy, but I couldn't do it without problems with pointers and other strange things.

What's is the standard way to do it?. Some code would be fantastic.

Thanks and regards.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, minor corrction:

Change

    strcat  (   pszOutBuffer,   pc);
    strcat  (   pszOutBuffer,   " ");

    pc  =   strtok  (   NULL,   " ");

to read

    strcat  (   pszOutBuffer,   pc);

    pc  =   strtok  (   NULL,   " ");

   if ( pc)
    strcat  (   pszOutBuffer,   " ");
beginning from the end of "String" look for a blank.
Then you get the position of the last word.
Now you can extract the two substrings using strcpy() and strncpy()

Try this code. Maybe you must modify it a little bit, I've written it "from brain to keyboard" and didn't test it.
But it should show the idea.

void Split (char *string, char *part1, char *part2)
{
   int  i;
   int len = strlen(string);

   for (i=len-1; i>=0 && i!=' '; i--)
      ;

   if (i >= 0)   // found a blank
   {
      strncpy(part1, string, i);
      part1[i] = 0;

      strncpy(part2, &string[i+1], len-i);
      part2[len-i] = 0;
   }
   else
   {
      part1[0] = 0;
      part2[0] = 0;
   }
}


}