用空格替换字符数组中的非字母字符

问题描述 投票:0回答:4

我想删除/替换 char 数组中的非字母字符,但它没有删除它,而是用 space 替换它。 例如,如果我输入

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 arrays
4个回答
3
投票

您可能想考虑使用更多 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;
}

注意以下事项:

  1. string
    +
    getline
    消除输入长度超限问题。
  2. isalpha
    检查字符是否是字母。
  3. “擦除删除”习惯用法可以为您处理棘手的左移。

2
投票

如果您只是要打印结果,则一次打印一个“传递”字符会更容易,并通过不打印来抑制其余字符。

此外,您应该使用

isalpha()

中的

<ctype.h>
来检查字符是否是字母,您的代码非常不可移植,因为它假设有关编码的奇怪事情。不要这样做。
    


0
投票
input[i] < 'A' || input[i] > 'z'

替换为

!isalpha(input[i])
:对于真正的可移植 C 和 C++,您不能假设 ASCII 编码,即使在 ASCII 中,大写和小写部分也不会“接触”。

如果你想真正

删除

字符,你应该向后运行循环。


0
投票

#include <stdio.h> #include <ctype.h> #include <string.h> int main() { char input[80]; char output[80]; printf("> "); scanf("%s", &input); int i = 0; int j = 0; while (i < sizeof(input)) { if (isalpha(input[i])) { input[j] = input[i]; ++j; } ++i; } input[j-1] = '\0'; printf("= %s\n", input); return 0; }

© www.soinside.com 2019 - 2024. All rights reserved.