David78
David78

Reputation: 23

extracting string occurrence in c

I have a string that look something like this:

long_str = "returns between paragraphs 20102/34.23\" - 9203 1232 \"test\" \"basic HTML\"";

Note: Quotes are part of the string.

int match(char *long_str){
    char * str;
    if ((str = strchr(long_str, '"')) != NULL) str++; // last " ?
    else return 1;
    return 0;
}

Using strstr I'm trying to get the whole substring between the last two quotes: "basic HTML". I'm just not quite sure what would be a good and efficient way of getting that match. I'm open to any other ideas on how to approach this. Thanks

Upvotes: 0

Views: 775

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753665

Assuming that you can't modify the source string, then I think you should look at a combination of strchr() and strrchr() - at least, if you want to use library functions for everything.

  • First use strrchr() to find the last quote.
  • Then repeatedly use strchr() to find quotes from the front, up to the time it returns the last quote found by strrchr().
  • The combination of the previous result and the result of strrchr() gives you the quotes around the string you are interested in.

Alternatively:

  • First use strrchr() to find the last quote.
  • Write a loop to search backwards from there to find the previous quote, remembering not to search before the start of the string in the case that it is malformed and contains only one quote.

Both will work. Depending on the balance of probabilities, it is quite possible that the loop will outperform even a highly optimized strchr() wrapped in a loop.

Upvotes: 0

user181548
user181548

Reputation:

#include <stdio.h>

char * long_str = 
"returns between paragraphs 20102/34.23\" - 9203 1232 \"test\" \"basic HTML\"";

int main ()
{
    char * probe;
    char * first_quote = 0;
    char * second_quote = 0;
    for (probe = long_str; * probe; probe++) {
        if (*probe == '"') {
            if (first_quote) {
                if (second_quote) {
                    first_quote = second_quote;
                    second_quote = probe;
                } else {
                    second_quote = probe;
                }
            } else {
                first_quote = probe;
            }
        }
    }
    printf ("%s\n", first_quote);
    printf ("%d-%d\n", first_quote - long_str, second_quote - long_str);
    return 0;
}

Upvotes: 1

Related Questions