题目要求如下:
要求将输入的字符串中指定字符去除,最简单的方式是通过对第1个字符串进行遍历,逐一比较其与字符是否相等,如果相等则跳过该字符,否则输出当前字符。
下面是1种简单的实现方式:
#include <stdio.h>
#include <string.h>
int main() {
char s[200] = {0};
while (gets(s) != NULL) {
char c;
//获取要替换的字符
scanf("%c", &c);
//获取第1个字符串的长度
int length = strlen(s);
for (int i = 0; i < length; ++i) {
if (s[i] != c) {
printf("%c", s[i]);
}
}
printf("\n");
getchar();
}
return 0;
}
由于输入的字符串中可能有空格,因此使用gets进行读取。而后面混合了scanf函数,因此需要使用getchar函数吸收输入的回车键,避免gets函数退出。
另外1种方式是使用strstr函数获取对应字符的位置,之后将其对应位置之前的字符输出。而再使用strncpy将原有字符串进行截断。
#include <stdio.h>
#include <string.h>
int main() {
char s[200] = {0};
while (scanf("%s", s) != EOF) {
char c[200] = {0};
scanf("%s", c);
long long pos = strstr(s, c) - s;
int l = strlen(c);
// 字符出现的位置
while (pos >= 0) {
for (int i = 0; i < pos; ++i) {
printf("%c", s[i]);
}
//截断字符串到字符出现位置
strncpy(s, s + pos + l, strlen(s + pos + l) + 1);
pos = strstr(s, c) - s;
}
// 输出剔除所有字符后的字符串
int length = strlen(s);
for (int i = 0; i < length; ++i) {
printf("%c", s[i]);
}
printf("\n");
}
return 0;
}
最后是最终通过后的结果: