【问题标题】:Split C string after identifier在标识符后拆分 C 字符串
【发布时间】:2014-12-11 01:14:50
【问题描述】:

快速问题:我想在最后一个“/”处拆分字符串文字(文件路径)。

所以,从这里:"/folder/new/new2/new3" 结果是:"/folder/new/new2"

所以基本上,我总是希望结果是提供的绝对路径后面的一个目录。

我一直在使用strtok 类似的东西来获取最后一个目录,但我不知道获取倒数第二个 目录的简单方法。 :

    char *last
    char *tok = strtok(dirPath, "/");
    while (tok != NULL)
    {
         last=tok;
         tok = strtok(NULL, "/");
    }

【问题讨论】:

  • 嗨,我没有。我只是查了一下,这可以完美地工作。我可以得到最后一个“/”的索引,然后在那里拆分字符串。我是 C 新手,所以其中一些功能对我来说是新的。谢谢!
  • cplusplus.com/reference/clibrary 是一个很好的资源。这是一个 C++ 网站,但它有很好的 C 库文档。
  • 下面提供的答案,说明路径名中的斜杠。

标签: c parsing strtok


【解决方案1】:

参考 user3121023 的建议,我使用了strrchr,然后在最后出现的“/”处放置了一个空终止符。

char str[] = "/folder/cat/hat/mat/ran/fan";
char * pch;
pch=strrchr(str,'/');
printf ("Last occurence of '/' found at %d \n",pch-str+1);
str[pch-str] = '\0';
printf("%s",str);

这很完美,打印的结果是“/folder/cat/hat/mat/ran”。

【讨论】:

  • 如果路径尾部有斜杠,此操作将失败。根据场景,两个尾部斜杠(即:符号链接目录遍历)是一个有效的场景。
  • 我将它用于我正在创建的虚拟 FAT 文件系统。不会有任何尾随斜杠。但对于一般应用来说是有效的。
  • 根据路径字符串生成的方式,在任何情况下仍然可能有一个斜杠。 unix.stackexchange.com/questions/1910/…
【解决方案2】:

哇,我在直 C 上生疏了,但是就这样吧。类似于您现有代码的循环通过使用 strstr 而不是 strtok 来查找最后一个斜杠的位置。从那里只需将字符串的一部分复制到该斜线即可。您还可以通过用空终止符覆盖最后一个斜杠来更改 dirPath,但这可能会导致内存泄漏(?),具体取决于您的代码还做了什么......

// find last slash
char *position = strstr(dirPath, "/");
while (strstr(position, "/") != NULL)
{
    position = strstr(position, "/");
}

// now "position" points at the last slash character
if(position) {
    char *answer = malloc(position - dirPath); // difference in POINTERS
    strncpy(answer, dirPath, position - dirPath);
    answer[position - dirPath] = `\0`; // null-terminate the result
}

【讨论】:

    【解决方案3】:

    我还没有编译和运行它。只是为了好玩。

    char* p = dirPath, *last = NULL;
    for(; *p; p++)
    {
       if (*p == '/')
          last = p;
    }
    
    if (last)
    {
        *last = 0;
        puts(dirPath);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多