I am trying to make a program so that when a string such as "cccaaaattt" is entered the output will be "cat"
Here is my code so far:
#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;
}
I commented on what I thought the code would have done.
It does not remove the right amount of character making my output "ccaatt"
Thanks for the help.
2 Answers 2
One extremely easy and efficient way to do this in C++ is to use std::unique
from the algorithm library and the erase
function of 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";
}
This will output:
xbczx
1 Comment
Whereas using std::unique
does the job, your error is that you increase your counter after erase
. The fixed implementation:
for (int i = 1; i < str.length(); /* No increment here */ ) {
if (str[i - 1] == str[i]) {
str.erase(i, 1);
} else {
++i;
}
}
args
(which is unused)