对字符串中的单词排序

来源:互联网 发布:淘宝什么是一块包邮 编辑:程序博客网 时间:2024/05/21 07:01
/*
对字符串中的单词排序
*/


#include <iostream>
#include <string>
using namespace std;


struct node
{
char s[100];


};








void main()
{
node str[100];
int k=0,j=0;;
char input[100];
cin.getline(input,100);//因为要接收' ',所以不能用cin
int n=0;
char *pin=input;
while(*pin!='\0')//提取单词
{
j=0;
while(*pin==' ' && *pin!='\0')
pin++;
while(*pin!=' '&& *pin!='\0')
{

str[k].s[j++]=*pin++;

}
str[k].s[j]='\0';
if(*pin!='\0')//不能少
{
k++;
n++;
}


}
cout<<n;


for(int i=0;i<n;i++)//冒泡排序
{
for(int j=0;j<n-1;j++)
{
//if(strcmp(str[j].s,str[j+1].s)>0)//按字母顺序排序
if(strlen(str[j].s)>strlen(str[j+1].s))//按单词长度排序
{
node tmp;
tmp=str[j];
str[j]=str[j+1];
str[j+1]=tmp;
}
}
}

for(int i=0;i<n;i++)
cout<<str[i].s<<endl;


}
0 0
原创粉丝点击