我的作业是删除随机字符串中的重复项。我的想法是使用 2 个循环来解决问题。
第一个将扫描字符串中的每个字符。 第二个将检查字符是否重复。如果是,则删除该字符。
string content = "Blah blah..."
for (int i = 0; i < content.size(); ++i) {
char check = content.at(i);
for (int j = i + 1; j < content.size() - 1; ++j) {
if (check == content.at(j)) {
content.erase(content.begin()+j);
}
}
}
问题是它不起作用。它总是删除错误的字符。似乎是索引问题,但我不明白为什么。
临时修复方法是将 content.erase(content.begin()+j);
更改为 content.erase( remove(content.begin() + i+1, content.结束(), 检查),content.end());
但我认为触发“按值删除”扫描不是一个好方法。我想用 2 个或更少的循环来完成。
任何想法将不胜感激:)
最佳答案
你的循环看起来像下面这样
#include <iostream>
#include <string>
int main()
{
std::string s = "Blah blah...";
std::cout << '\"' << s << '\"' << std::endl;
for ( std::string::size_type i = 0; i < s.size(); i++ )
{
std::string::size_type j = i + 1;
while ( j < s.size() )
{
if ( s[i] == s[j] )
{
s.erase( j, 1 );
}
else
{
++j;
}
}
}
std::cout << '\"' << s << '\"' << std::endl;
return 0;
}
输出是
"Blah blah..."
"Blah b."
还有许多其他使用标准算法的方法。例如
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string s = "Blah blah...";
std::cout << '\"' << s << '\"' << std::endl;
auto last = s.end();
for ( auto first = s.begin(); first != last; ++first )
{
last = std::remove( std::next( first ), last, *first );
}
s.erase( last, s.end() );
std::cout << '\"' << s << '\"' << std::endl;
return 0;
}
输出与前面的代码示例相同
"Blah blah..."
"Blah b."
关于c++ - 删除字符串算法中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24496063/