Can you explain how to remove duplicates from string not character array

Please explain with the help of code so that its easy to understand

@KetanPandey
Feel free to ask if you have any doubt.

string s = "ccooodding";
string ans = "";
for (auto c : s) {
	if (ans.back() != c)
		ans += c;
}
cout << ans;

Can we solve it without using ans string.Means can we modify the same string so that it does not contain duplicates characters

Sure

string s = "ccooodding";
int l = 0;
for (int i = 0; i < s.size(); i++) {
	if (s[i] != s[l]) {
		s[++l] = s[i];
	}
}
s.resize(l + 1);
cout << s;

thanku so much for ur help

1 Like