用c语言和c++程序分别实现用户输入一个字符串和一个字符。然后,程序遍历整个字符串,统计指定字符出现的次数,并在找到指定字符时将其删除后输出新的字符串
时间: 2024-01-22 08:17:29 浏览: 42
C语言实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100], ch;
int len, i, count = 0;
printf("Enter a string: ");
gets(str);
printf("Enter a character: ");
scanf("%c", &ch);
len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] == ch) {
count++;
continue;
}
printf("%c", str[i]);
}
if (count == 0) {
printf("\nThe character '%c' is not found in the string.\n", ch);
} else {
printf("\n'%c' is found %d times in the string and removed.\n", ch, count);
}
return 0;
}
```
C++实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string str;
char ch;
int len, i, count = 0;
cout << "Enter a string: ";
getline(cin, str);
cout << "Enter a character: ";
cin >> ch;
len = str.length();
for (i = 0; i < len; i++) {
if (str[i] == ch) {
count++;
continue;
}
cout << str[i];
}
if (count == 0) {
cout << "\nThe character '" << ch << "' is not found in the string." << endl;
} else {
cout << "\n'" << ch << "' is found " << count << " times in the string and removed." << endl;
}
return 0;
}
```
阅读全文