用strtok分割故障

时间:2014-09-15 12:38:15

标签: c

#include<stdio.h>
#include<string.h>
int main(){
        char path[] = "/fs/lost+found";
        char* temp;
        temp =  strtok(path,"lost+found");
        while(temp != NULL){
                printf("\n %s \n",temp);
                temp = strtok(path,"lost+found");
        }
        return 0;
}

我想提取丢失+找到的字符串。上面的程序进入无限循环并打印&#34; /&#34;在分隔符之前&#34;丢失+找到&#34;

[root @ rs]#。/ a.out 分段错误

4 个答案:

答案 0 :(得分:3)

你犯了两个错误(你可以从here轻松发现)。

  1. strtok()分隔符作为第二个参数。在您的情况下,此分隔符不是lost+found,而是合理/

  2. while块中strtok函数的第一个参数必须为NULL才能使函数继续扫描以前成功调用函数的位置。

  3. 最后,您必须使用strcmp()来发现已处理的令牌是否是您要查找的字符串。

    所以:

     ...
    while (temp != NULL) {
        if (strcmp("lost+found", temp) == 0)
            printf ("%s\n", temp); // found
    
        temp = strtok (NULL, "/");
      }
     ... // not found
    

答案 1 :(得分:3)

来自男人3 strtok:

  

char * strtok(char * str,const char * delim);

  strtok()函数将字符串解析为一系列标记。上   第一次调用strtok()时要解析的字符串应该是   在str中指定在每个后续调用中应该解析相同的   string,str应为NULL。

修正:

#include<stdio.h>
#include<string.h>

int main(){
    char path[] = "/fs/lost+found";
    char* temp;
    temp =  strtok(path,"/");
                     // ^^^  different delimiter
    do {
        printf("%s\n", temp);
        temp = strtok(NULL, "/");
                   // ^^^^ each subsequent call to strtok with NULL as 1st argument
    } while (temp != NULL);
    return 0;
}

它将打印出“fs”和“lost + found”标记。您可以添加一些检查temp是否当前具有您正在寻找的值,然后您可以存储在其他变量中。

答案 2 :(得分:1)

delim参数指定一组字符,用于分隔已解析字符串中的标记。

您为strtok提供的第二个参数提供了一组分隔符,用于标记给定字符串,而不是用于提取特定字符串

使用strstr

temp = strstr(path,"lost+found");

这将返回指向您要搜索的子字符串的指针

答案 3 :(得分:0)

您无法更改字符串文字,strtok()将修改其正在处理的字符串。