c - 删除 char 数组中的非字母字符

标签 c arrays

我想删除/替换字符数组中的非字母字符,但它不是删除它,而是用空格替换它。 例如,如果我输入 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;
}

注意以下几点:

  1. string + getline消除输入长度超限的问题。
  2. isalpha检查字符是否是字母。
  3. erase-remove idiom 会为你处理棘手的左移。

关于c - 删除 char 数组中的非字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39636757/

相关文章:

c - 管道末端重定向(C shell)

java - 多维数组中的 ArrayIndexOutOfBoundsException

c - 转换为字节数组后打印值

arrays - MATLAB:删除矩阵的一些元素

arrays - 如何向 powershell 对象添加新属性

c - 引用外部全局变量惨遭失败

C 中的字符 IO

c - 分配给函数的参数太多?

c - 程序在这里如何使用堆栈?

c++ - 字符串流到数组