Write a function that compresses recurring characters for a given string. For example, aaabbbbccccdd returns a3b4c4d2.
The code proceeds as follows:
- Input the string into the function.
- Initialize a string to store the results.
- Store the first character in the string as the temporary character.
- Initialize an integer counter to one.
- Go through each character in the string.
- If the current character is equal to the temporary character then increment the counter.
- Otherwise append the temporary character and its counter to the results string.
- Reset the counter to one.
- Set the temporary character as the current character.
- Return the results string.
string compress(const string & myString) { string result; char last = myString[0]; int counter = 1; for (int i = 1; i < myString.length(); i++) { if (myString[i] == last) counter++; else { result.append(last); result.append(itoa(counter)); last = myString[i]; counter = 1; } return result; }