Reputation: 57
i am writing a C program and one of the issues i have is to extract a word between two words as below.
ac_auto_lvalue[] =
"ONLY / GROUP: OTHERS EXAMPLE /-----------------------------";
I need to extract the word between "Group:" and the "/", the two words (Group:" & "/") will always be there but the words in between can change and in some cases there might be nothing... ( in the above example output would be "OTHERS EXAMPLE"
can anyone help me with a C snippet for the above?
Upvotes: 3
Views: 12385
Reputation: 726809
Take a look at the strstr
function. It lets you find a pointer to the first occurrence of a specific string (say, "Group:"
) inside another string. Once you have two pointers (to the beginning and to the end of your string) you can allocate enough memory using malloc
(don't forget the terminating zero '\0'
), use memcpy
to copy the characters, and finally zero-terminate your string.
int main() {
char ac_auto_lvalue[] = "ONLY / GROUP: OTHERS EXAMPLE /-----------------------------";
// Adding 7 to compensate for the length of "GROUP: "
const char *p1 = strstr(ac_auto_lvalue, "GROUP: ")+7;
const char *p2 = strstr(p1, " /");
size_t len = p2-p1;
char *res = (char*)malloc(sizeof(char)*(len+1));
strncpy(res, p1, len);
res[len] = '\0';
printf("'%s'\n", res);
return 0;
}
Upvotes: 8
Reputation: 688
Use strstr for Group, increment that pointer by the length of Group (6).
Upvotes: 1