• C

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.
xilgaroAsked:
Who is Participating?
 
jkrConnect With a Mentor Commented:
Basically, you want to remove 'Three' from the above string. The following code will do that:

char* RemoveFromString ( char* pszString, char*, pszWord, char* pszOutBuffer)
{
  char* pc;

  pc = strtok ( pszString, " ");

  while ( pc)
  {
    if  (   !strcmp (   pc, pszWord))
            continue;

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

    pc  =   strtok  (   NULL,   " ");
  }

  return    (   pszOutBuffer);
}

It copies each word from 'pszString' (->String) to 'pszOutBuffer' (->String_2), but omits 'pszWord' (->String_1).

Make sure that pszOutBuffer is large enough ;-)

Feel free to ask if you need more information!
0
 
jkrCommented:
Sorry, minor corrction:

Change

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

    pc  =   strtok  (   NULL,   " ");

to read

    strcat  (   pszOutBuffer,   pc);

    pc  =   strtok  (   NULL,   " ");

   if ( pc)
    strcat  (   pszOutBuffer,   " ");
0
 
PacmanCommented:
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;
   }
}


}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.