您的位置:首页 > 其它

对字符串中的单词排序

2014-03-23 11:14 190 查看
/*

对字符串中的单词排序

*/

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: