How to delete a specified element in a character array …
In C language, character arrays cannot directly remove specific elements, but the effect of deleting a specific element can be achieved through other means. One common method is:
- Iterate through the character array to locate the position of the element to be deleted.
- Move all elements after this position forward by one space.
- Reducing the length of an array by 1 is equivalent to deleting an element.
Here is an example code:
#include <stdio.h>
#include <string.h>
void deleteElement(char array[], int length, char element) {
int i, j;
// 找到要删除的元素的位置
for (i = 0; i < length; i++) {
if (array[i] == element) {
break;
}
}
// 将该位置之后的所有元素向前移动一位
for (j = i; j < length - 1; j++) {
array[j] = array[j+1];
}
// 将数组的长度减1
length--;
// 输出删除元素后的数组
for (i = 0; i < length; i++) {
printf("%c ", array[i]);
}
printf("\n");
}
int main() {
char str[] = "Hello";
int length = strlen(str);
char element = 'l';
deleteElement(str, length, element);
return 0;
}
When running the above code, the character array with deleted elements will output as “H e o”.