c - C 中去除字符串末尾

标签 c string parsing pointer-arithmetic

我需要一个函数来删除 )从字符串末尾开始的字符。 例如,hello,world)应转换为 hello,world .

我写了这个:

char *a="hello,world)";
int a_len=strlen(a);
*(a+a_len-1)='\0';
printf("%s", a);

但输出中没有显示任何内容。

最佳答案

理想情况下,您应该收到分段冲突运行时错误。

您已分配了一个指向驻留在只读内存中的字符串文字的指针。尝试修改它是不好的!

尝试将其复制到堆栈上

char a[] ="hello,world)";

如果您确实必须使用动态内存(请在您的问题中写下),那么您必须在那里手动复制字符串:

char *a = malloc(sizeof("hello,world)"));
memcpy(a, "hello,world)", sizeof("hello,world)"));
int a_len=strlen(a);
a[a_len - 1] = '\0';

或者,您也可以让 printf 截断您的字符串:

printf("%.*s", strlen(a) - 1, a);

正如 Basile 指出的那样,还有 strdup

char * a = strndup("hello,world)", sizeof("hello,world)") -2);

请注意,这里我们必须截断两个字符,因为 sizeof 包含空终止符,但 strndup 始终会添加一个字符。

关于c - C 中去除字符串末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21703706/

相关文章:

python - 在 Python 中中止 HTMLParser 处理

c - Varnish C VRT变量/功能

java - 从字符串生成器中删除字符

python - 在 Python 中使用 Split,同时转义括号中的分隔符

c++ - 语言分析的二叉树实现 - 子节点作为节点 : does not work

perl - 在 Perl 中优雅地解析刚性数据

c - 指向接受常量和非常量参数的函数的指针

C语言编程难度

c - 兰德功能改进

python - python open语句中的反斜杠错误