c++ - 从 char 数组中删除双空格

标签 c++

尝试编写一个程序来清理字符串。但是由于某种原因,我遇到了双空格问题。它要么只删除一半的多余空间,要么永远运行。

char input[246] = {'\0'};
    bool done = false;
    int count = 0;
    while (!done)
    {
        cout << "Hello, please enter a string to translate." << endl;
        cin.get(input, 246);
    }

for (int i = 0; i <= 246; i++)
    {
        if (input[i] != '\0')
        {
            count++;
        }
    }

for (int i = 0; i <= count - 1;)  //remove double spaces
    {
        while (input[i] == ' ' && input[i + 1] == ' ')
        {
            for (int q = i + 1; q <= (count - 1) - i; q++)
            {
                input[q] = input[q + 1];
            }
            count--;
        }
        else
        {
            i++;
        }
    }

最佳答案

您可以使用 std::unique使用自定义谓词删除重复空格:

auto last = std::unique(&input[0], input + strlen(input), [](char const& a, char const &b)
{
    return std::isspace(a) && std::isspace(b);
});
*last = '\0';  // Terminate string

关于c++ - 从 char 数组中删除双空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58407774/

相关文章:

C++ DAL 设计 - 将外键表包含为复合对象

c++ - 将数字乘以矩阵

c++ - 模板特化或函数重载

c++ - 排除时间测试

c++ - 简化重载的类函数

c++ - 我收到错误 C2440 :

c++ - 如何在不使用另一个文件的情况下剪切文件?

c++ - G++ 新的 ABI 问题

c++ - 使用 OpenMP 实现的线程池

C++ boost :asio convert socket to stream?