C++输入一个字符串,将它们按照字母由小到大的顺序排列并输出

如题所述

#include<iostream>

#include<cstring>

using namespace std;

void main()

{

 char str[1000],temp;

 int i,j,len;

 gets(str);

    len=strlen(str);

 for(i=0;i<len-1;i++)

  for(j=0;j<len-i-1;j++)

   if(str[j]>str[j+1])

   {

    temp=str[j];

    str[j]=str[j+1];

    str[j+1]=temp;

   }

  puts(str);

}

追问

谢谢!不过可以简单解释一下吗?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-17
#include<iostream>
using namespace std;
int main()
{
char string[50];
for(int i=0;i<50;i++)
{
cin>>string[i];
if(string[i]=='0')
break;
}
if(i==50)
{
cout<<"输入字符过多。"<<endl;
}
else
{
char temp;
for(int m=0;m<i-1;m++)
{
for(int n=m+1;n<i;n++)
{
if(string[m]>string[n])
{
temp=string[m];
string[m]=string[n];
string[n]=temp;
}
}
}
for(int j=0;j<i;j++)
cout<<string[j];
cout<<endl;
}
return 0;
}
第2个回答  2013-05-17
#include <iostream>
#include <cctype>
#include <algorithm>
using namespace std;
// 字母分大小写
bool op(char a, char b)
{
    return tolower(a) < tolower(b);
}
int main()
{
    char s[256];
    cin >> s;
    sort(s, s+strlen(s), op);
    cout << s;
}

第3个回答  2013-05-17
char letter='a';
for(int i=0;i<26;i++)
cout<<letter++;追问

好像不对啊,字母没按大小输出吧

相似回答