How to remove a pair of same adjacent characters from string in C++

1 Answer

0 votes
#include <iostream>

void removeAdjacentPair(std::string &s) {
    for (int i = 0; i < s.size() - 1; i++) {
         if (s[i] == s[i + 1]) {
             s.erase(i, 2);
             if (i != 0) i--;
         }
    }
}

int main()
{
	std::string s = "aabcccdeeffffgac";
	
	removeAdjacentPair(s);

	std::cout << s;

	return 0;
}



/*
run:

bcdgac

*/

 



answered Jun 20, 2020 by avibootz
...