【问题标题】:Check if Substring is in string more than once?检查子字符串是否不止一次在字符串中?
【发布时间】:2015-03-14 16:28:07
【问题描述】:

假设我有一个文件:

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,但这似乎不起作用,任何帮助将不胜感激。

【问题讨论】:

    标签: c file parsing pointers


    【解决方案1】:

    但是b 始终是y 的值(之前的逗号值)

    这是因为您又开始从头开始搜索逗号,因此不再获取与 'd' 关联的逗号,而是再次获取与 'f' 关联的逗号。

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

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

    用这个:

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

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

    【讨论】:

    • 你的意思是它会在这里得到值 4 吗?不是 5 个?
    • @user3739406 是的,你会得到4
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2011-02-07
    • 2013-04-29
    • 2013-12-13
    相关资源
    最近更新 更多