C strtok()无法正确标记吗?

我已经尝试了一段时间,现在我完全不知道如何解决这个问题。我有一个相当不错的规模项目,并且我无数次使用strtok而没有任何问题,但是在这里不起作用。请帮助:(

编辑:我正在寻找前缀删除而不是strtok。如果有人感到困惑并用谷歌搜索,我将把它留在这里。

这是有问题的代码

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

int main()
{
   char root[1000]; 
   char home[1000];

   strcpy(root,"/Users/me/Desktop/my-project"); // this is working
   strcpy(home,"/Users/me/Desktop/my-project/home"); // this is working

   strtok(home,root); // here's the problem

   printf("%s",home);
}

结果1:

/Users/me/Desktop/my-project/h

我也尝试过:

char *ptr = strtok(home,root);

printf("%s",ptr);

结果2:

h

都不应该都返回/home吗?

gg85806539 回答:C strtok()无法正确标记吗?

正如@paxdiablo所指出的,当我在整个项目中都使用它时(我还没睡过,所以请原谅我),strtok(char * str,char * delimiters)列出了一个定界符。

我实际上想做的是从root字符串中删除home子字符串。

由于它们将始终以相同的子字符串/Users/me/Desktop/my-project开头,因此我可以在home结束后立即找到root的唯一部分,并且可以很容易地做到这一点:>

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

int main()
{
   char root[1000]; 
   char home[1000];

   strcpy(root,"/Users/mbp/Desktop/my-project");
   strcpy(home,"/Users/mbp/Desktop/my-project/home");

   int n = strlen(root); // length of the root string

   // where to copy,from where to start copying,how many to copy
   strncpy(home,home + n,strlen(home)-1); 

   printf("%s",home);
}

所以我要做的是:

  1. 获取根的长度以知道其结尾
  2. 通过将零件从home[n]复制到home[strlen(home)-1]来覆盖家庭存储的内容

结果:

/home
本文链接:https://www.f2er.com/3130517.html

大家都在问