请用C++编写一个程序实现删除字符串中重复的字符,并分别统计,重复的字符个数。例如:原字符串为“a

2025-04-19 18:38:32
推荐回答(1个)
回答1:

确定是c++? STL string+unique+count,可以很容易解决:

#include 
#include 
#include 

using namespace std;

int main(int argc, char const *argv[])
{
    string str = "abcabcbbced";
    string ustr(str);
    
    sort(ustr.begin(), ustr.end());
    ustr.erase(unique(ustr.begin(), ustr.end()), ustr.end() );
    cout << ustr << endl;
    for (string::iterator it=ustr.begin(); it != ustr.end(); ++it)
        cout << *it << " " << count(str.begin(), str.end(), *it) << endl;
    
    return 0;
}

运行:

a 2
b 4
c 3
d 1
e 1