从键盘输入6个字符串(仅仅包含英文字母和数字),对这6个字符串从小到大排列并输出结果。

 从键盘输入6个字符串(仅仅包含英文字母和数字),对这6个字符串从小到大排列并输出结果。

方法一:利用字符指针数组



#include <stdio.h>

#include <string.h>

int main()

{

    char one[100];//定义接收第1个字符串

    char two[100];//定义接收第2个字符串

   char three[100];//定义接收第3个字符串

    char four[100];//定义接收第4个字符串

    char five[100];//定义接收第5个字符串

    char six[100];//定义接收第一个字符串

    printf("请输入第1个字符串(仅包含英文字母和数字):");

   gets(one);

    printf("请输入第2个字符串(仅包含英文字母和数字):");

   gets(two);

    printf("请输入第3个字符串(仅包含英文字母和数字):");

   gets(three);

    printf("请输入第4个字符串(仅包含英文字母和数字):");

   gets(four);

    printf("请输入第5个字符串(仅包含英文字母和数字):");

   gets(five);

    printf("请输入第6个字符串(仅包含英文字母和数字):");

   gets(six);

    char *temp;//定义temp变量用于交换

   char *sort[]={one,two,three,four,five,six};//定义字符串指针数组存放 6个字符串的地址

//    

   for(int i=0;i<6;i++)//选择排序

    {

        

       for(int j=0;j<5;j++)

        {

            

           if(strcmp(sort[i],sort[j])<0)//字符串比较函数strcmp

            {

               //交换两个变量的地址

                temp=sort[i];

                sort[i]=sort[j];

                sort[j]=temp;

            }

        }

    }

    //循环输出

    printf("排序完成\n");

   for(int i=0;i<6;i++)

    {

       printf("%s\n",sort[i]);

    }

    

}

方法2:利用二维字符数组

#import <Foundation/Foundation.h>

int main(int argc,constchar * argv[]) {

    @autoreleasepool {

        

       char ch[6][50];//创建二维字符数组存储 

       for (int i =0; i<6; i++) {

    //循环输入

           printf("键入第%d个字符串:(仅包含英文字母和数字)",i+1);

    //存进二维字符数组中,(%s不可输入空格)

           scanf(" %s",ch[i]);

            

        }

        //下面是利用选择排序

       for (int i =0; i<6; i++) {

           for (int j =1; j<5; j++) {

               if (strcmp(ch[i], ch[j])<0) {

                    

                   char temp[50];

    //交换数组中的值

                   strcpy(temp, ch[i]);

                   strcpy(ch[i], ch[j]);

                   strcpy(ch[j],temp);

                }

            }

        }

       printf("由小大到排序完毕:");

       for (int i =0; i<6; i++) {

           printf("%s ",ch[i]);

        }

       printf("\n");

    }

   return0;

}

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值