从字符串中删除所有重复字符 (STL) [英] Remove all duplicate characters from a string (STL)
本文介绍了从字符串中删除所有重复字符 (STL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能完成以下程序?
谢谢.
void RemoveDuplicates (string& input)
{
string nonRepeatedChars (input);
sort(nonRepeatedChars.begin(), nonRepeatedChars.end());
//cout << nonRepeatedChars <<endl;
string::iterator it = unique(nonRepeatedChars.begin(), nonRepeatedChars.end());
//cout << nonRepeatedChars <<endl;
nonRepeatedChars.erase(it, nonRepeatedChars.end());
cout << "nonRepeatedChars = "<< nonRepeatedChars <<endl;
for(string::iterator i = input.begin(); i != input.end(); i++)
{
cout << "*i = " << *i <<endl;
size_t found = nonRepeatedChars.find(*i);
cout << "found = "<< found <<endl;
if (found != string::npos)
{
input.erase(i);
cout << "input = " << input <<endl;
}
else
{
nonRepeatedChars.erase(found, 1);
cout << "nonRepeatedChars = "<< nonRepeatedChars <<endl;
}
}
cout << "Final Input = " << input <<endl;
}
推荐答案
解决方案一如既往的简单:
Solution simple as always:
void RemoveDuplicates (std::string& input) {
std::string::iterator it = std::unique(input.begin(), input.end());
input.erase(it, input.end());
std::cout << "New input = "<< input << std::endl;
}
返回新字符串的另一种解决方案:
Another solution to return a new string:
std::string RemoveDuplicates (const std::string& input) {
std::string newT(input);
std::string::iterator it = std::unique(newT.begin(), newT.end());
newT.erase(it, newT.end());
return newT;
}
如果想要的结果是 hello -> helo 那么解决方案是:
If desired result is hello -> helo then the solution is :
std::string RemoveDuplicates (const std::string& input) {
std::string newInput;
const char * prev = nullptr;
for (const auto & ch : input) {
if (!prev || (*prev != ch)) {
newInput.push_back(ch);
}
prev = &ch;
}
return newInput;
}
如果您需要保存字符顺序并删除重复项:
If you need to save order of chars and remove duplicates:
std::string RemoveDuplicates (const std::string& input) {
std::string newInput;
std::set<char> addedChars;
for (const auto & ch : input) {
if (addedChars.end() == addedChars.find(ch)) {
newInput.push_back(ch);
addedChars.insert(ch);
}
}
return newInput;
}
这篇关于从字符串中删除所有重复字符 (STL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文