drunk_coder
drunk_coder

Reputation: 31

Erase() doesn't work C++

Given a string named question = " this isn't a relevant question , is it??? ". You have to replace consecutive spaces by only one space. I have an idea using erase() in std::string but I don't know why it does not work. Here my code:

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

Upvotes: 0

Views: 2068

Answers (3)

Le Hoang Duong
Le Hoang Duong

Reputation: 31

You can use unique in <algorithm> in the following way.

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);

Upvotes: 3

Didier Trosset
Didier Trosset

Reputation: 37427

If you really want C++, use regex.

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

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234655

You shouldn't increase i if you've erased an element. If you do, you'll skip over elements.

Also, your fancy stopping condition will lead to undefined behaviour on a blank string, and in cases where the string ends with two spaces.

Upvotes: 3

Related Questions