Reputation: 23
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
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.
strrchr()
to find the last quote.strchr()
to find quotes from the front, up to the time it returns the last quote found by strrchr()
.strrchr()
gives you the quotes around the string you are interested in.Alternatively:
strrchr()
to find the last 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
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