I am trying to make a small test function that when passed a char * will search that string for a certain sub string and then output the next characters after the white space until the next whitespace.
I made a basic implementation using strstr() and strncpy() but this method is kind of static and only works for one search term at a time with a fixed output of the next characters.
int ParseCommand(char *command)
{
char *pSearch = strstr(command, CommandOne);
char str[100];
if (pSearch != NULL)
{
pSearch += strlen(CommandOne) + 1;
strncpy(str, pSearch, 2);
printf("%s\n\n", str);
}
printf("%s\n", command);
return 0;
}
What this code sample does is if you pass say ParseCommand("ten hats 10 are cool") and CommandOne is equal to "hats" the function will output "10". Although this does work it performs the operations too statically and will make it hard for it to search for more commands within char *command. I essentially need something that will loop through command until strstr() finds a command inside the passed string and then copy everything from after the command to the next white space.
I know how I would search for the commands (I am going to create a pointer char array with all my search terms and loop through them all until strstr() does not return null) but how about would I copy the next “word” after the searched term?
Overall I need some pseudocode logic to search for search terms within a sentence and then copy the data preseeding it until the next whitespace is reached. (Copy the next word after the search term in the sentence.)
I whipped a quick prototype and it seems to work.
Test it with,
ParseCommand("ten hats 10 are cool", "hats")and it returns10.HTH.