九度题目:字符串排序(1135)

来源:互联网 发布:java远程调用dll 编辑:程序博客网 时间:2024/05/19 16:36

题目描述:

先输入你要输入的字符串的个数。然后换行输入该组字符串。每个字符串以回车结束,每个字符串少于一百个字符。
如果在输入过程中输入的一个字符串为“stop”,也结束输入。
然后将这输入的该组字符串按每个字符串的长度,由小到大排序,按排序结果输出字符串。

输入:

字符串的个数,以及该组字符串。每个字符串以‘\n’结束。如果输入字符串为“stop”,也结束输入.

输出:

可能有多组测试数据,对于每组数据,
将输入的所有字符串按长度由小到大排序输出(如果有“stop”,不输出“stop”)。

样例输入:
5sky is greycoldvery coldstop3it is good enough to be proud ofgoodit is quite good
样例输出:
coldvery coldsky is greygoodit is quite goodit is good enough to be proud of
提示:

根据输入的字符串个数来动态分配存储空间(采用new()函数)。每个字符串会少于100个字符。
测试数据有多组,注意使用while()循环输入。

需注意的几点:

1)有gets()的时候注意用getchar()吸收'\n'

2)qsort()的参数

3)struct ToSort *s;


#include <stdio.h>#include <stdlib.h>#include <string.h>struct ToSort {    char str[100];    int length;};int Comp(const void *p1, const void *p2){    const struct ToSort *q1 = p1;    const struct ToSort *q2 = p2;        return q1->length - q2->length;}int main() {    int n, i;    char temp[100];    struct ToSort *s;    while (scanf("%d", &n) != EOF) {        getchar();        s = (struct ToSort*)malloc(n*sizeof(struct ToSort));        int count = 0;        for (i = 0; i < n; i++) {            gets(temp);            if (strcmp(temp, "stop") == 0)                 break;            else {                strcpy(s[i].str, temp);                s[i].length = strlen(temp);                count++;            }        }        qsort(s, count, sizeof(struct ToSort), Comp);        for (i = 0; i < count; i++) {            printf("%s\n", s[i].str);        }    }    return 0;}