c - 在C中的某个字符之后删除字符串的结尾

标签 c string

我试图在 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;
}

最佳答案

在 C 中,当您像这样编写文字字符串时: char* foo= "/一/二/三/二";

它们是不可变的,这意味着它们嵌入到可执行文件中并且是只读的。

尝试修改只读数据时出现访问冲突(崩溃)。

相反,您可以将字符串声明为字符数组而不是文字字符串。

#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';

    return;
}

int main ( void )
{

    char foo[] = "/one/two/three/two";
    deleteEnd(foo);
    printf ("%s\n", foo);

    return 0;
}

关于c - 在C中的某个字符之后删除字符串的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323797/

相关文章:

c++ - 是否可以在 C 或 C++ 中基于 JSON 动态创建 if 语句

C: switch 语句错误: "this is the first entry overlapping that value"

android - 通过 Intent 将 JSONObject 传递给另一个 Activity

java - 正则表达式 - 堆栈跟踪 - 匹配除 java 包名称之外的所有网站地址

Java:当您不需要任何分隔符时如何拆分字符串

c - 错误: Initializer Element is not constant (c language)

c - C中结构的前向声明?

c - select() 遇到问题

java - 为什么字符串输出中出现空值?

PHP,str_pad unicode 问题