Я пытаюсь сделать программу, так что, когда вводится строка, такая как "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"
Спасибо за помощь.
Один очень простой и эффективный способ сделать это в 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
В то время как использование 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;
}
}
Подсказка: если у вас есть 4 последовательных одинаковых символа, у вас есть 2 пары. Вы правильно удаляете вторую половину каждой пары.
args
(который не используется)