1

I need an efficient function that extracts first second and rest of the sentence into three variables.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Alex Xander
  • 3,903
  • 14
  • 36
  • 43

3 Answers3

12

Easy way: Use strtok() or strtok_r to get the first two tokens, which will remove them from the string, so the string itself will be your third token you were looking for.

Hard way: Parse it yourself :(

Strtok is in the C string library, and will mutate your original string so be careful, copy the string first if it needs to remain intact.

Possible Example:

//#include <string.h>

char input[] ="first second third forth";
char delimiter[] = " ";
char *firstWord, *secondWord, *remainder, *context;

int inputLength = strlen(input);
char *inputCopy = (char*) calloc(inputLength + 1, sizeof(char));
strncpy(inputCopy, input, inputLength);

firstWord = strtok_r (inputCopy, delimiter, &context);
secondWord = strtok_r (NULL, delimiter, &context);
remainder = context;

printf("%s\n", firstWord);
printf("%s\n", secondWord);
printf("%s\n", remainder);

getchar();
free(inputCopy);

This should work just fine and be threadsafe with the original string unmutated.

Alex Moore
  • 3,415
  • 1
  • 23
  • 39
2

You need to define the delimiters first. There are a few problems with strtok (it modifies its argument, for one, which may land you in trouble). I prefer to read in the string and run a custom parser which may range from sscanf to a full-blown parser. Please post some more detail.

dirkgently
  • 108,024
  • 16
  • 131
  • 187
  • +1 `sscanf()` would work well, since I expect "words" means "anything not whitespace," making the conversion specifier easy, and should neatly avoid all the problems with `strtok()` and friends. – Chris Lutz Oct 13 '09 at 14:42
1

strtok()

Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168