检查 Substring 是否多次出现在字符串中?

Check if Substring is in string more than once?

假设我有一个文件:

f56,5 d23,4

我正在获取 'f' 和逗号之后的值(和 d 一样)所以我这样做: (使用 fgets 读取文件时)

while (fgets(buf,100,file) != NULL)
{
    temp = strstr(buf,"f"); //where temp is a (char * )
    if(temp != NULL)
    {  
        //An int defined previously 
        x = atol(temp+1); //get the value 56
        temp = strstr(buf,","); //get the value 5
        y = atol(temp+1); //get the value 5
    }

    temp = strstr(buf,"d");
    if(temp != NULL)
    {
        a = atol(temp+1); //get the value 24
        temp = strstr(buf,","); //get the value 4?
        b = atol(temp+1); //get the value 4?
    }


}

这种方法可行,但是,a 和 b 的值不正确,a 有时为真,但 b 始终为 y 的值(前一个逗号值)。我不太确定如何在这里继续,我尝试使用另一个指针在代码中使用 strstr 但这似乎不起作用,任何帮助将不胜感激。

however b is always the value of y (previous comma value)

这是因为您再次从头开始搜索逗号,所以您没有获得与 'd' 相关联的逗号,而是再次获得与 'f' 相关联的逗号。

要解决此问题,请替换此行

temp = strstr(buf, ","); //get the value 4?

有了这个:

temp = strstr(temp+1, ","); //yes, get the value 4!

这将开始搜索 'd' 之后的下一个逗号,为您提供正确的结果。