使用STL从字符串中删除重复的字符 [英] Removing duplicate characters from string using STL
问题描述
是否有一种方法可以从字符串中删除重复的字符,例如可以从向量中将其删除,如下所示
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
推荐答案
C ++算法和容器设计的全部要点是,算法尽可能与容器无关。
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());
即使是老式C字符串也可以使用–差别很小,您不能擦除
的尾巴,您需要通过重新设置空终止符来手动截断它们(并且没有开始
和 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).
这篇关于使用STL从字符串中删除重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!