Search code examples
csubstringextractc-stringsfunction-definition

Extracting a Certain portion of a String (Substring) in C


I am trying to extract the name of a store from strings that are stored as char arrays using the language C. Each one contains the price of an item and the store it is located at. I have many strings that follow this format, but I have provided I few examples below:

199 at Amazon
139 at L.L.Bean
379.99 at Best Buy
345 at Nordstrom

How could I extract the name of the store from these strings? Thank you in advance.


Solution

  • const char *sought = "at ";
    char *pos = strstr(str, sought);
    if(pos != NULL)
    {
        pos += strlen(sought);
        // pos now points to the part of the string after "at";
    }
    else
    {
        // sought was not find in str
    }
    

    If you want to extract a portion after pos, but not the entire remaining string, you can use memcpy:

    const char *sought = "o "; 
    char *str = "You have the right to remain silent";
    char *pos = strstr(str, sought);
    
    if(pos != NULL)
    {
        char word[7];
    
        pos += strlen(sought); 
        memcpy(word, pos, 6);
        word[6] = '\0';
        // word now contains "remain\0"
    }