5

Is there a way to remove duplicate characters from a string like they can be removed from vectors as below

sort( vec.begin(), vec.end() );
vec.erase( unique( vec.begin(), vec.end() ), vec.end() );

or do I just have to code up a basic solution for it? What I have thought:

I could add all the characters into a set

4
  • 3
    It's exactly the same for a string as for a vector. Commented Jan 14, 2014 at 18:42
  • That depends on what you mean by "duplicate" characters. Does a string "ABACADAF" have duplicate As? Or would you just want "AABACAD" to remove the first A in the double AA? Commented Jan 14, 2014 at 18:42
  • Why would you go for an O(n log(n)) solution while you can do it in O(n) as explained here in the Second method? Commented Jan 14, 2014 at 18:44
  • Thanks turns out i was missing out the "str" part from str.erase(...) and was ending up with an error thinking this cant be done.. my bad.. Commented Jan 14, 2014 at 19:04

1 Answer 1

14

The whole point of C++’ algorithm and container design is that the algorithms are – as far as possible – container agnostic.

So the same algorithm that works on vectors works – of course! – on strings.

std::sort(str.begin(), str.end());
str.erase(std::unique(str.begin(), str.end()), str.end());

The same even works on old-style C strings – with the small difference that you cannot erase their tails, you need to manually truncate them by re-setting the null terminating character (and there are no begin and end member functions so you’d use pointers to the first and one-past-last character).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.