在c中提取字符串出现

时间:2010-04-04 05:08:02

标签: c strstr

我有一个看起来像这样的字符串:

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

注意:引号是字符串的一部分。

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

使用strstr我试图获取最后两个引号之间的整个子字符串:"basic HTML"。我只是不太确定什么是一个好的和有效的方式来获得这场比赛。我对如何处理这个问题的任何其他想法持开放态度。感谢

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

假设您无法修改源字符串,那么我认为您应该查看strchr()strrchr()的组合 - 至少,如果您想将库函数用于所有内容。< / p>

  • 首先使用strrchr()查找最后一个引用。
  • 然后重复使用strchr()从前面查找引号,直到它返回strrchr()找到的最后一个引号为止。
  • 上一个结果与strrchr()结果的组合为您提供了您感兴趣的字符串的引号。

可替换地:

  • 首先使用strrchr()查找最后一个引用。
  • 写一个循环从那里向后搜索以找到之前的引用,记住在字符串开头之前不要搜索它是否格式错误并且只包含一个引号。

两者都有效。根据概率的平衡,即使循环中包含高度优化的strchr(),循环也很可能会胜过。

相关问题