C extract word from a string between two words

12,052

Solution 1

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;
}

Solution 2

Use strstr for Group, increment that pointer by the length of Group (6).

Share:
12,052
Vikas
Author by

Vikas

Updated on June 29, 2022

Comments

  • Vikas
    Vikas almost 2 years

    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?

  • tartar
    tartar about 12 years
    do the same thing with character /. let say address for the pointer pointing the end of Group (which is 'p') is held by char* a, and address of '/' is help by another pointer char*b, then you can use memcpy for copying between these two pointers.