编写c语言程序,删除宇行串中的某个字符。(宇符串、要删除的字符都由用户 人键益输人,有则删除 —所谓删除就是后序的元素往前覆盖,无则提示"该字 付不仔在。)
时间: 2023-07-15 22:10:08 浏览: 95
以下是一个简单的C语言程序,用于从一个字符串中删除指定的字符:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char ch, *p, *q;
printf("请输入一个字符串:");
scanf("%s", str);
printf("请输入要删除的字符:");
scanf(" %c", &ch);
p = q = str;
while (*p) {
if (*p != ch) {
*q = *p;
q++;
}
p++;
}
*q = '\0';
if (strcmp(str, q) == 0) {
printf("该字符不存在。\n");
} else {
printf("删除后的字符串为:%s\n", str);
}
return 0;
}
```
程序首先提示用户输入一个字符串和要删除的字符。然后,使用两个指针 `p` 和 `q` 遍历字符串,并将不等于要删除的字符的元素复制到前面的位置。最后,将字符串末尾的 `q` 设定为结束符号。
如果要删除的字符不存在,则输出提示信息。否则,输出删除后的字符串。
相关问题
c语言输人一行宇行。分别统计出其中英文宇母、空格、数字和其他字符的个数
在C语言中,你可以使用`ctype.h`库提供的函数来识别字符种类,并使用`getchar()`从用户输入读取字符。下面是一个简单的示例程序,它统计字母、空格、数字和非字母数字字符的数量:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
int alpha_count = 0, space_count = 0, digit_count = 0, other_count = 0;
char ch;
while ((ch = getchar()) != '\n') { // 循环直到遇到换行符
if (isalpha(ch)) { // 检查是否是字母
alpha_count++;
} else if (isspace(ch)) { // 检查是否是空格
space_count++;
} else if (isdigit(ch)) { // 检查是否是数字
digit_count++;
} else { // 其他字符
other_count++;
}
}
printf("Alphabets: %d\n", alpha_count);
printf("Spaces: %d\n", space_count);
printf("Digits: %d\n", digit_count);
printf("Other characters: %d\n", other_count);
return 0;
}
```
此程序会持续接收用户输入直到遇到换行符,然后统计每种类型的字符。
编写程序,输入一个字符串,再输入一个宇符,在宇行书中期除输入的宇符,形成新的字行事并 输出,程序保存为2.c
以下是实现此功能的 C 语言程序代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100], ch, new_str[100];
int i, j = 0;
printf("请输入字符串:");
gets(str);
printf("请输入要删除的字符:");
scanf("%c", &ch);
for(i = 0; i < strlen(str); i++) {
if(str[i] != ch) {
new_str[j] = str[i];
j++;
}
}
new_str[j] = '\0';
printf("删除 %c 后的新字符串为:%s\n", ch, new_str);
return 0;
}
```
注意:此程序使用了 gets 函数,该函数不安全,容易造成缓冲区溢出等问题。建议使用 fgets 函数代替。
阅读全文
相关推荐
















