我想删除/替换字符数组中的非字母字符,但它不是删除它,而是用空格替换它。 例如,如果我输入 hello123hello,它将输出为 hello hello。 我希望它将其输出为 hellohello,而不带额外的空格。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char input[80];
char output[80];
printf("> ");
scanf("%s", &input);
int i = 0;
while (i < sizeof(input))
{
if (input[i] != '\0' && input[i] < 'A' || input[i] > 'z')
input[i] = ' ';
{
i++;
}
}
printf("= %s\n", input);
return 0;
}
最佳答案
您可能需要考虑更多的 C++ 方式来完成任务:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main() {
string s;
getline(cin, s);
s.erase(remove_if(begin(s), end(s), [](char c){ return !isalpha(c); }));
cout << s << endl;
}
注意以下几点:
-
string
+getline
消除输入长度超限的问题。 -
isalpha
检查字符是否是字母。 - erase-remove idiom 会为你处理棘手的左移。
关于c - 删除 char 数组中的非字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39636757/