c语言输入一个字符串,删除指定的字符。 【输入输出样例】 【样例说明】 提示符后冒号为英文字符,无空格 输出结束有换行符。
时间: 2024-10-06 11:06:42 浏览: 97
在 C 语言中,你可以通过遍历字符串并检查每个字符是否是你想要删除的特定字符,然后构建一个新的字符串来实现这个功能。这里有一个简单的例子:
```c
#include <stdio.h>
#include <string.h>
void deleteChar(char *str, char delChar) {
int i, j = 0;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] != delChar) {
str[j++] = str[i];
}
}
// 如果删除了字符,需要更新字符串长度,并在末尾添加'\0'
str[j] = '\0';
}
int main() {
char input[100], delChar;
printf("请输入一个字符串: ");
fgets(input, sizeof(input), stdin); // 注意fgets会保留换行符
input[strcspn(input, "\n")] = '\0'; // 去除fgets留下的换行符
printf("请输入要删除的字符: ");
scanf("%c", &delChar);
deleteChar(input, delChar);
printf("删除 '%c' 后的字符串是: %s\n", delChar, input);
return 0;
}
```
在这个程序中,`deleteChar` 函数接收一个字符串和一个待删除的字符作为参数,然后遍历字符串,跳过该字符,将其他字符复制到新位置。`main` 函数则用于获取用户输入,调用 `deleteChar` 并打印结果。
**相关问题--:**
1. 使用fgets代替scanf读取字符串有何优点?
2. 如果字符串中有多个相同的待删字符,上述代码会怎么处理?
3. 如何修改代码以便支持连续删除多个指定字符?
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/octet-stream](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)