Удалить последовательные повторяющиеся значения в строке

0

Я пытаюсь сделать программу, так что, когда вводится строка, такая как "cccaaaattt", выход будет "cat",

Вот мой код:

#include "stdafx.h"
#include <iostream>
#include <string>


using namespace std;

int main(array<System::String ^> ^args)
{
    string str = "";//create an empty string variable named str
    std::cout << "What word do you want to remove duplicate characters from?";
    cin >> str; //fill the str variable with the word the user whants to remove duplicate consecutive characters from
    char current;//create a new char variable named current
    char lastChar;//create a new char variable named lastChar for the previos character in the string

for (int i = 1; i < str.length(); i++){ //iterate through until it reaches the end of the string
    lastChar = str[i - 1]; //set lastChar to the previos char in the string
    current = str[i];//set current to the current char in the string
    if (lastChar == current){//if the lastChar and the current are equal (the string has two consecutive characters
        str.erase(i,1);//erase the current character
    }

}
cout << str << endl; //display the new string
system("pause");
return 0;

}

Я прокомментировал, что я думал, что код сделал бы.

Он не удаляет правильное количество символов, делая мой вывод "ccaatt"

Спасибо за помощь.

  • 0
    Я начал переписывать его как C ++ / CLI, но это почти чистый C ++ за исключением args (который не используется)
  • 0
    Подсказка: если у вас есть 4 одинаковых персонажа подряд, у вас есть 2 пары. Вы правильно удаляете вторую половину каждой пары.
Теги:

3 ответа

3
Лучший ответ

Один очень простой и эффективный способ сделать это в C++ - использовать std::unique из библиотеки алгоритмов и функцию erase std::string.

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string x("xxbbbbccccczzzzxxxx");
    x.erase(std::unique(x.begin(), x.end()), x.end());
    std::cout << x << "\n";
}

Это приведет к выводу:

xbczx

  • 0
    Я новичок, было бы что-то простое, как это. Спасибо. Ваше имя пользователя актуально :)
2

В то время как использование std::unique выполняет задание, ваша ошибка заключается в том, что вы увеличиваете счетчик после erase. Фиксированная реализация:

for (int i = 1; i < str.length(); /* No increment here */ ) {
    if (str[i - 1] == str[i]) {
        str.erase(i, 1);
    } else {
        ++i;
    }
}
0

Подсказка: если у вас есть 4 последовательных одинаковых символа, у вас есть 2 пары. Вы правильно удаляете вторую половину каждой пары.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню