定义一个函数删除字符串s中字符ch,并用主函数调用
时间: 2023-04-06 07:00:26 浏览: 63
好的,我可以回答这个问题。以下是函数的定义和主函数的调用:
```c
#include <stdio.h>
#include <string.h>
void deleteChar(char s[], char ch) {
int len = strlen(s);
int i, j;
for (i = 0, j = 0; i < len; i++) {
if (s[i] != ch) {
s[j++] = s[i];
}
}
s[j] = '\0';
}
int main() {
char s[100], ch;
printf("请输入一个字符串:");
scanf("%s", s);
printf("请输入要删除的字符:");
scanf(" %c", &ch);
deleteChar(s, ch);
printf("删除后的字符串为:%s\n", s);
return 0;
}
```
这个函数可以删除字符串s中的字符ch,并将结果存储在原字符串s中。主函数调用了这个函数,并输出了删除后的字符串。
相关问题
定义一个函数删除字符串s中字符ch并用主函数调用
好的,我可以回答这个问题。以下是删除字符串s中字符ch的函数定义:
```c
void deleteChar(char *s, char ch) {
int i, j;
for (i = 0, j = 0; s[i] != '\0'; i++) {
if (s[i] != ch) {
s[j++] = s[i];
}
}
s[j] = '\0';
}
```
在这个函数中,我们使用了两个指针i和j,i用于遍历字符串s,j用于记录删除字符ch后的新字符串的长度。当遍历到不是字符ch的字符时,将其复制到新字符串中,并将j加1。最后在新字符串的末尾添加一个空字符'\0',表示字符串的结束。
以下是主函数调用的示例:
```c
int main() {
char s[] = "hello world";
char ch = 'l';
deleteChar(s, ch);
printf("%s\n", s); // 输出 "heo word"
return 0;
}
```
在主函数中,我们定义了一个字符串s和一个要删除的字符ch,然后调用deleteChar函数删除字符串s中的字符ch,并输出删除后的字符串。
用c语言编写一个函数,删除字符串s中的特殊字符ch
好的,以下是用 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 函数等读取空白行的问题。