我尝试在C语言中根据某个特定字符结束字符串。由于该程序将与文件系统一起使用,因此该字符将被重复使用,我需要找到该字符的最后一个出现并删除其后的所有内容。
我在互联网上找到了一些东西,但它不起作用,我不知道为什么。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void deleteEnd (char* myStr){
printf ("%s\n", myStr);
char *del = &myStr[strlen(myStr)];
while (del > myStr && *del != '/')
del--;
if (*del== '/')
*del= '\0'; // the program crashes here
return;
}
int main ( void )
{
char* foo= "/one/two/three/two";
deleteEnd(foo);
printf ("%s\n", foo);
return 0;
}
这段代码基本上是查找最后一个 '/' 字符并将空终止符放在那里。理论上它是可行的,但实际上却不是。
顺便说一下,如果我的方法是错误的,有更好的方法吗?
谢谢。
**编辑:根据建议,我用 "strrchr()" 替换了我的代码,但仍然没有结果:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void deleteEnd (char* myStr){
char *lastslash;
if (lastslash = strrchr(myStr, '/'))
*lastslash = '\0'; // the code still crashes here.
return;
}
int main ( void )
{
char* foo= "/one/two/three/two";
deleteEnd(foo);
printf ("%s\n", foo);
return 0;
}
char *lastslash; if (lastslash = strrchr(myStr, '/')) *lastslash = '\0';
- EOFstrlen()-1
是错误的。考虑一个空字符串:strlen("")
的结果是零,你肯定不想引用strlen("")-1
。 - EOF