How to remove duplicate spaces from a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <algorithm>

using std::cout;
using std::endl;
using std::string;

bool BothAreSpaces(char lhs, char rhs) { return (lhs == rhs) && (lhs == ' '); }

int main()
{
	string s = "c,      c++,    java, php,   python";

	// remove duplicate spaces
	string::iterator new_end = std::unique(s.begin(), s.end(), BothAreSpaces);
	s.erase(new_end, s.end());

	cout << s << endl;
		
	return 0;
}

/*
run:

c, c++, java, php, python

*/

 



answered Jan 27, 2018 by avibootz

Related questions

...