0

I am in need of searching through an array looking for a key word and obtain the word right after that. Something like this but in c Need to get a string after a "word" in a string in c#. I thought about using strtok but it will destroy the array from the tokenizing and I need read without messing with the array. Is there any way I can do this?

array[50] = "Hi, I am victor";
// I want the word after the "am" without destroying or messing up the array 
Community
  • 1
  • 1
user3577156
  • 19
  • 1
  • 2
  • Why not just make a copy if the array before using the destructive call? If you know that will get the job done? – Alex Zywicki Jun 10 '14 at 22:55
  • I haven't tried this on C but when I did a copy in arduino, the back up array still got messed with without me ever touching it. Maybe I did something wrong but that experience made me kind of not want to do that. – user3577156 Jun 11 '14 at 04:00

2 Answers2

4

Use strstr().

char* am = strstr( array , "am " ) ;
char* next_word = NULL ;
if( am )
    next_word = am + strlen( "am ") ;

The last line will move the pointer to the position of the word after the "am ".

This assumes all words are separated by a single space and nothing else. You might want to check for other characters and multiple spaces. I hope you get the idea.

this
  • 5,229
  • 1
  • 22
  • 51
0

You can use strtok, you just need to copy the string to a temp string before handing it to strtok:

char array[50] = "Hi, I am victor";
char tmp[50];
char tokensep[] = " \n\r"; 
char *tok_ptr;

snprintf(tmp,50,"%s",array);

token = strtok_r(tmp, tokensep, &tok_ptr);  
while(token != NULL & strcmp(token,"am") != 0)
{
    token = strtok_r(NULL, tokensep, &tok_ptr); 
}
token = strtok_r(NULL, tokensep, &tok_ptr); 
// token now contains the name