c - 如何删除数组中特定位置的字符?

标签 c arrays

所以,我正在尝试从数组中添加和删除字符。我有一个工作正常的 add_to_array 函数。它准确地打印出它应该打印的内容。但是,我似乎无法从数组末尾删除字符。我尝试时的代码是:

void delete_array(char *q, char f)
{
  char *blah = q;
  while(*blah != '\0')
  {
    blah--;
  }
  *blah = f;
  blah--;
  *blah = '\0';
 }

我的 add_to_array 代码完全相同,只是它是 blah++ 并且我认为删除一个字符正好相反。它可以编译,但会打印“段错误(核心转储)”作为输出。我哪里错了?感谢您的任何建议/帮助。

最佳答案

像这样:

#include <stdio.h>

void delete_array(char *str, char ch){
//To remove the specified character from a string
    char *to, *from;

    for(to = from = str; *from != '\0'; ++from){
        if(*from != ch)
            *to++ = *from;
    }
    *to = '\0';
}
int main(void){
    char str[] = "application";

    delete_array(str, 'p');
    printf("%s\n", str);//alication
    return 0;
}
<小时/>

如果删除特定位置的字符,您需要在参数中包含该位置。

#include <stdio.h>

void delete_array(char *str, size_t pos){
//Delete the character of the position pos.
    char *p;

    for(p = str + pos; *p = p[1] ; ++p)
        ;
}
int main(void){
    char str[] = "application";

    delete_array(str, 3);
    printf("%s\n", str);//appication
    return 0;
}

关于c - 如何删除数组中特定位置的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804142/

相关文章:

c - 双向链表中的结构内部结构

c - EVP_PKEY_sign 和 EVP_DigestSignInit 之间的区别?

c - 警告 : assignment discards qualifiers from pointer target type

javascript - 对使用 `map` 创建的数组上 `new` 的行为感到困惑

c++ - 我在 C++ 数组初始化方面遇到了麻烦

c - 如何使用 C 和 WinAPI 将包含特殊字符的文本复制到剪贴板?

c - 在 C 中实现队列

c++ - 使用函数创建数组 - Objective-C++

javascript - 对数组进行循环和计数

java - 如何为数组中的每个对象创建一个数组?