- 题目描述:
-
先输入你要输入的字符串的个数。然后换行输入该组字符串。每个字符串以回车结束,每个字符串少于一百个字符。
如果在输入过程中输入的一个字符串为“stop”,也结束输入。
然后将这输入的该组字符串按每个字符串的长度,由小到大排序,按排序结果输出字符串。
- 输入:
-
字符串的个数,以及该组字符串。每个字符串以‘ ’结束。如果输入字符串为“stop”,也结束输入.
- 输出:
-
可能有多组测试数据,对于每组数据,
将输入的所有字符串按长度由小到大排序输出(如果有“stop”,不输出“stop”)。
- 样例输入:
-
5 sky is grey cold very cold stop 3 it is good enough to be proud of good it is quite good
- 样例输出:
-
cold very cold sky is grey good it is quite good it is good enough to be proud of
- 提示:
-
根据输入的字符串个数来动态分配存储空间(采用new()函数)。每个字符串会少于100个字符。
测试数据有多组,注意使用while()循环输入。
思路:
直接冒泡排序或快速排序即可。
更优的解法:设一个字符串指针数组,分别指向各字符串,对该指针数组排序,效率更高。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char s[100][100];
char tmpn[80], tmps[100];
int i, j, n;
while (gets(tmpn))
{
n = atoi(tmpn);
for (i=0; i<n; i++)
{
gets(s[i]);
if (strcmp(s[i], "stop") == 0)
break;
}
n = i;
for (i=0; i<n-1; i++)
{
for (j=0; j<n-1-i; j++)
{
if (strlen(s[j]) > strlen(s[j+1]))
{
strcpy(tmps, s[j]);
strcpy(s[j], s[j+1]);
strcpy(s[j+1], tmps);
}
}
}
for (i=0; i<n; i++)
printf("%s
", s[i]);
}
return 0;
}
/**************************************************************
Problem: 1135
User: liangrx06
Language: C
Result: Accepted
Time:0 ms
Memory:916 kb
****************************************************************/