从键盘输入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;
}