【问题标题】:Delimiting file path in C using strtok()使用 strtok() 在 C 中分隔文件路径
【发布时间】:2013-12-30 04:13:52
【问题描述】:

在我当前的代码中,我尝试传入一个文件路径,用 "/" 分隔文件路径,然后使用 for 循环检查每个分隔值与名为 categories 的数组中的每个元素。如果数组中的任何元素匹配为使用strstr() 的子字符串,它将返回元素的值,否则将返回"Others"
我设法产生了我想要的输出,但是我意识到只要类别数组中有偶数个元素,输出将是文件路径中的值的 1,例如
如果文件路径是

"/a/b/Lib/Contact/c"

如果类别是

char *categories[] = {"Library","Applications","Contact","dsdfd"};  

输出将是b
这是我的代码供您参考:

const char *categorize(char*path)
{
    int i = 0;
    char str[1024];
    char *token;
    char *delim = "/";
    char *categories[] = {"Library","Applications","Contact","dsdfd"};
    bool check = false;

    strcpy(str,path);
    token = strtok(str,delim);
    while (token !=NULL)
    {
        if(check == true)
            break;

         //printf("%s\n",token);
        for (i = 0; i <(sizeof(categories)/sizeof(char*)); i++)
        {
            if(categories[i] == NULL)
                break;
            if(strstr(token, categories[i]))
            {
                check = true;
                break;
            }
        }
        token = strtok (NULL, delim);
    }
    if (check == true)
        return "Others";
    else
    return categories[i];

}

编辑:我遇到了另一个问题。如果文件路径不包含任何子字符串,我尝试使用测试用例。它应该返回“Others”,但它返回的是“/”。
Edit2:我已经通过将 if 语句更改为 check == true 解决了这个问题。但是,我意识到我这里的代码不好,@LưuVĩnhPhúc 和 @fasked 在 cmets 中提到,我希望可能修复它。

【问题讨论】:

  • sizeof(categories) 不是数组的长度
  • .. sizeof(categories)/sizeof(char*)
  • 您还返回指向本地 C 字符串的指针。大多数编译器不会在堆栈上分配字符串,但它们没有义务。
  • @fasked ,抱歉,您能进一步解释一下吗?我真的不明白你想表达什么。对不起
  • @user2541163 查看接受的答案stackoverflow.com/questions/1224042/…stackoverflow.com/questions/6897914/…。第一个定义问题,第二个给出答案。

标签: c delimiter


【解决方案1】:

把你的代码改成

 for (i = 0; i <(sizeof(categories)/sizeof(char*)); i++)

sizeof(categories) 将为您提供 16 个字节(大小为 4 char*),您必须将其与每个 char* 大小分开以获得类别中的元素数量;

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 2021-10-11
    • 2015-02-09
    • 2011-06-03
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多