如何将一个字符串顺序化?
比如有几个字符串s[0]="awervd";
s[1]="ethbvasdf";
...
然后按照英语字母的顺序把每个字符串顺序化之后得到
s[0]="adervw";
s[1]="abdefhst";
...
想这样做的话,要怎么做?
谢谢!
程序代码:
#include <iostream>
#include<cstring>
#include <set>
using namespace std;
int main()
{
char *s = "ethbvasdfbbcca";
multiset<char> ms;
//将所有的字符插入到容器中
for(int i = 0; i < strlen(s); i++)
ms.insert(s[i]);
//输出
for(char c : ms)
cout << c << " ";
cout << endl;
//或者利用迭代器输出
multiset<char>::iterator it = ms.begin();
while(it != ms.end()){
cout << *it << "-";
it++;
}
cout << endl;
return 0;
}
[此贴子已经被作者于2018-11-12 12:27编辑过]
程序代码:#include <iostream>
#include <string>
#include <climits>
std::string foo( const std::string& s )
{
size_t buf[ CHAR_MAX-CHAR_MIN+1 ] = {};
for( size_t i=0; i!=s.size(); ++i )
++buf[ s[i]-CHAR_MIN ];
std::string r;
for( size_t i=0; i!=sizeof(buf)/sizeof(*buf); ++i ) // sizeof(buf)/sizeof(*buf) 可以直接写成 std::size(buf)
r += std::string( buf[i], i+CHAR_MIN );
return r;
}
int main( void )
{
std::cout << foo("awervd") << std::endl;
std::cout << foo("ethbvasdf") << std::endl;
}
程序代码:
#include <iostream>
#include<cstring>
#include <set>
#include <string>
using namespace std;
string sortStr(const string str)
{
multiset<char> ms;
string value;
//将所有的字符插入到容器中
for (int i = 0; i < str.length(); i++)
ms.insert(str[i]); //str的元素就是char
for (char c : ms)
value += c;
return value;
}
int main()
{
string s = "ethbvasdfbbcca";
cout << sortStr(s);
return 0;
}