用c语言编写一个函数,删除字符串s中的特殊字符ch
时间: 2024-05-07 16:17:10 浏览: 12
好的,以下是用 C 语言编写一个函数,删除字符串 s 中的特殊字符 ch 的代码:
```
#include <stdio.h>
#include <string.h>
void remove_char(char *s, char ch) {
int i, j;
int n = strlen(s);
for (i = 0, j = 0; i < n; i++) {
if (s[i] != ch) {
s[j] = s[i];
j++;
}
}
s[j] = '\0';
}
int main() {
char s[100], ch;
printf("请输入一个字符串: ");
scanf("%s", s);
getchar(); // 消耗掉回车符
printf("请输入要删除的特殊字符: ");
scanf("%c", &ch);
remove_char(s, ch);
printf("删除特殊字符后的字符串为: %s\n", s);
return 0;
}
```
不要忘记在调用 scanf 函数后,消耗掉输入的回车符,否则可能导致后续 fgets 函数和 gets 函数等读取空白行的问题。
相关问题
用C语言,编写函数,删除字符串中的给定字符
下面是一个示例C语言函数,可以删除字符串中的给定字符:
```c
#include <stdio.h>
#include <string.h>
void delete_char(char *str, char ch) {
int i, j;
for (i = j = 0; str[i] != '\0'; i++) {
if (str[i] != ch) {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char str[100], ch;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter the character to delete: ");
scanf("%c", &ch);
delete_char(str, ch);
printf("Result: %s\n", str);
return 0;
}
```
这个函数接受两个参数:一个字符串和一个字符。它遍历字符串中的每个字符,如果字符不等于给定字符,则将其添加到新字符串中。最后,新字符串以空字符结尾,并替换原始字符串。
在主函数中,我们使用fgets函数读取输入字符串,然后使用scanf函数读取要删除的字符。最后,我们调用delete_char函数并打印结果。
用c语言实现编写函数,删除字符串中的给定字符
以下是用 C 语言实现删除字符串中给定字符的函数:
```c
#include <stdio.h>
#include <string.h>
void delete_char(char *str, char ch) {
int len = strlen(str);
int i, j;
for (i = 0, j = 0; i < len; i++) {
if (str[i] != ch) {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
}
int main() {
char str[100];
char ch;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
printf("Enter a character to delete: ");
scanf("%c", &ch);
delete_char(str, ch);
printf("String after deletion: %s\n", str);
return 0;
}
```
这个函数接受一个字符串和一个字符作为输入,然后删除字符串中所有出现的给定字符。该函数使用两个指针 `i` 和 `j` 遍历字符串,当遇到不是给定字符的字符时,将其复制到新字符串中,并将 `j` 指针向前移动。最后,将新字符串的结尾设为 `'\0'` 即可。