擦除() 不起作用C++

Erase() doesn't work C++

本文关键字:C++ 不起作用 擦除      更新时间:2023-10-16

给定一个名为 question = " this isn't a relevant question , is it??? "的字符串。您只需将连续的空间替换为一个空间。我有一个想法在std :: string中使用erase((,但我不知道为什么它不起作用。这里我的代码:

    for (int i = 1; question[i]; i++)
        while (question[i] == ' ' && question[i - 1] == ' ')
             question.erase(i, 1);

如果您删除了元素,则不应增加i。如果这样做,您将跳过元素。

另外,您的幻想停止条件将导致空白字符串上的不确定行为,如果字符串以两个空格结束。

您可以在<algorithm>中使用unique

std::string::iterator it = std::unique(question.begin(), question.end(), [](const char& a, const char & b) { return ((a == ' ') && (b == ' ')); });
std::string output_string(question.begin(), it);

如果您真的想要C ,请使用正则

#include <regex>
std::string question=" this      isn't a   relevant question , is it???     ";
std::string replaced = std::regex_replace(question, std::regex(" +"), " ");