给定一个名为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);发布于 2017-04-27 16:56:00
如果你已经删除了一个元素,你不应该增加i。如果这样做,您将跳过元素。
此外,如果字符串以两个空格结束,您的特殊停止条件将导致空白字符串上的未定义行为。
发布于 2017-04-27 17:53:28
您可以通过以下方式在<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);发布于 2017-04-27 17:12:09
如果你真的想要C++,那就使用正则表达式。
#include <regex>
std::string question=" this isn't a relevant question , is it??? ";
std::string replaced = std::regex_replace(question, std::regex(" +"), " ");https://stackoverflow.com/questions/43653078
复制相似问题