【哈工大C语言作业实验题】:13-2作业

题目

输入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[80],char str2[80]){
    int len1 = strlen(str1),len2=strlen(str2),i;
    for(i=0;i<len1 &&i<len2;i++){
        if(str1[i]<str2[i]){
            return 1;
        }
        if(str1[i]>str2[i]){
            return 0;
        }
    }
}
int main(){
    char str[10][80],temp[80],min[80];
    int i,j,pos;
    for(i=0;i<10;i++){
        gets(str[i]);
    }
    //printf("\n");
    for(i=0;i<10;i++){
        strcpy(min,str[i]);
        pos=i;
        for(j=i+1;j<10;j++){
            if(cmp(str[j],min)==1){
            //  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=0;i<10;i++){
        printf("%s\n",str[i]);
    }
    //printf("%d",cmp("new","china"));
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值