在C语言中,删除字符串中的特定字符可以通过多种方法实现。以下是几种常见的方法:
方法一:使用循环和条件判断
```c
include include void delchar(char s[], char c) { int i, j = 0; for (i = 0; s[i] != '\0'; i++) { if (s[i] != c) { s[j++] = s[i]; } } s[j] = '\0'; // 在字符串末尾加上'\0' } int main() { char s; printf("请输入字符串: "); gets(s); printf("输入要删除的字符: "); char c; scanf("%c", &c); delchar(s, c); printf("删除之后为: %s\n", s); return 0; } ``` 方法二:使用标准库函数 `strcpy()` ```c include include void delchar(char *str, char c) { char *src = str; char *dst = str; while (*src) { if (*src != c) { *dst++ = *src; } src++; } *dst = '\0'; // 在字符串末尾加上'\0' } int main() { char s; printf("请输入字符串: "); gets(s); printf("输入要删除的字符: "); char c; scanf("%c", &c); delchar(s, c); printf("删除之后为: %s\n", s); return 0; } ``` 方法三:使用指针操作 ```c include include void delchar(char *str, char c) { char *p = str; while (*p) { if (*p != c) { *str++ = *p; } p++; } *str = '\0'; // 在字符串末尾加上'\0' } int main() { char s; printf("请输入字符串: "); gets(s); printf("输入要删除的字符: "); char c; scanf("%c", &c); delchar(s, c); printf("删除之后为: %s\n", s); return 0; } ``` 方法四:使用 `del` 函数 ```c include include void del(char str[], char c) { int j = 0; for (int i = 0; str[i] != '\0'; i++) { if (str[i] != c) { str[j++] = str[i]; } } str[j] = '\0'; // 在字符串末尾加上'\0' } int main() { char s; printf("请输入字符串: "); gets(s); printf("输入要删除的字符: "); char c; scanf("%c", &c); del(s, c); printf("删除之后为: %s\n", s); return 0; } ``` 方法五:使用 `deletechar` 函数