Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...