如何在C中按值"删除"数组中的每个元素

Sat*_*aty 0 c arrays for-loop while-loop

我一直试图解决这个问题大约5天..找不到任何解决方案请发送帮助.我应该实现一个函数来按值"删除"数组中的每个元素.假设我的数组是"Hello",我想删除每个"l".到目前为止,我只能删除一次.顺便说一下,请记住我不允许使用指针来实现这个功能......(我们学校还没有学到这一点)这是我的代码:

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

void strdel(char array[], char c);

int main(void)
{
    char source[40];
    printf("\nStrdel test: ");
    strcpy(source, "Hello");
    printf("\nsource = %s", source);
    strdel(source, 'l');
    printf("\nStrdel: new source = %s", source);
    return 0;
}

void strdel(char array[], char c)
{
    int string_lenght;
    int i;
    for (string_lenght = 0; array[string_lenght] != '\0'; string_lenght++) {} 

    for (i = 0; i < string_lenght; i++) {
        if (array[i] == c) {
            for (i = i; array[i] != '\0'; ++i)
                array[i] = array[i + 1];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

chu*_*ica 5

简单使用2个索引,一个用于阅读,一个用于写入. @Carl Norum

void strdel(char array[], char c) {
  int read_index = 0;
  int write_index = 0;
  while (array[read_index] != '\0') {
    if (array[read_index] != c) {
      array[write_index] = array[read_index];
      write_index++;  // Only advance write_index when a character is copied
    }
    read_index++;     // Always advance read_index
  }
  array[write_index] = '\0';
}
Run Code Online (Sandbox Code Playgroud)

具有O(n)性能,比使用for()O(n*n)的嵌套循环快得多.


细节:

OP:顺便提一下,我不允许使用指针来实现这个功能.

请注意,arrayin void strdel(char array[], char c)是一个指针,即使它看起来像一个数组.

int对于学习者和大量代码,数组索引是可以的,但更好用size_t. int可能缺乏所需的范围.Type size_t是一种无符号类型,对于数组索引需求既不太窄也不太宽.这对于很长的字符串很重要.