2

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.

Jarod42
226k15 gold badges210 silver badges344 bronze badges
asked Dec 27, 2014 at 2:10
2
  • I started retagging it as C++/CLI but tbh it's almost pure C++ except for args (which is unused) Commented Dec 27, 2014 at 2:12
  • Hint: when you have 4 consecutive identical characters, you have 2 pairs. You correctly remove the second half of each pair. Commented Dec 27, 2014 at 2:14

2 Answers 2

9

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

answered Dec 27, 2014 at 2:16

1 Comment

I new there would be something simple like this. Thank you. Your user name is relevant :)
1

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;
 }
}
answered Dec 27, 2014 at 9:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.