天天看点

【哈工大C语言作业实验题】:13-2作业题目吐槽代码(已经accepted)

题目

输入10个单词,将10个单词排序后输出。请用二维字符数组编程实现。

提示:

1.输入的一个字符串中可能存在空格,如Guo Ping

2.字符串的长度最大为80

输入输出样例:

Input sample:

world

china

new

hello

good

you

me

apple

fens

help

Output sample:

apple

china

fens

good

hello

help

me

new

world

you

吐槽

要吐槽的是,这个题很简单,我却花了很长的时间去做,原因就是卡在了思考上面

给几个有用的背景知识,字符串赋值:strcpy函数

然后字符二维数组,每一行就代表着一行字符串,有了这个思路这个题就比较好做了

自己出问题的地方出在比较函数上!

代码(已经accepted)

#include <stdio.h>
#include <string.h>
int cmp(char str1[],char str2[]){
    int len1 = strlen(str1),len2=strlen(str2),i;
    for(i=;i<len1 &&i<len2;i++){
        if(str1[i]<str2[i]){
            return ;
        }
        if(str1[i]>str2[i]){
            return ;
        }
    }
}
int main(){
    char str[][],temp[],min[];
    int i,j,pos;
    for(i=;i<;i++){
        gets(str[i]);
    }
    //printf("\n");
    for(i=;i<;i++){
        strcpy(min,str[i]);
        pos=i;
        for(j=i+;j<;j++){
            if(cmp(str[j],min)==){
            //  printf("过程 j %d ",j);
            //  printf("min %s\n",min);
                strcpy(min,str[j]);
                pos = j;
            }
        }
        //cout<<"i "<<i<<" pos "<<pos<<endl;
    //  printf(" i %d pos %d \n",i,pos);
        strcpy(temp,str[i]);
        strcpy(str[i],str[pos]);
        strcpy(str[pos],temp);
    }
    for(i=;i<;i++){
        printf("%s\n",str[i]);
    }
    //printf("%d",cmp("new","china"));
    return ;
}
           

继续阅读