代码思路:定义一个二维字符串数组,用冒泡排序,去将字符串排序。
用strcmp去比较字符串大小,比较字符串大小的原理是字符所对应的阿斯克码值的和。
用strcpy去冒泡排序中的关键一步
外层循环循环一次,冒泡排序一次,打印一次。具体实现看下述代码。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
int n;
scanf("%d", &n);
int i, j;
char temp[100]; //暂存数组
char str[100][100];//定义二维字符串数组
for (i = 0; i < n; i++)
{
scanf("%s", &str[i]);//读取二维字符串数组
}
for (i = 0; i < n-1/*自身不用排序*/; i++) //冒泡排序
{
for (j = 0; j < n - 1-i/*每次排序会排好一次*/; j++)
{
if (strcmp(str[j], str[j + 1]) > 0)//strcmp中如果前者大于后者则返回1,等于返回0,小于返回-1;
{
strcpy(temp,str[j]);//是把后面的值赋给前面的值
strcpy(str[j], str[j+1]);
strcpy(str[j + 1], temp);
}
}
printf("Sorting No.%d\n\n", i + 1);
for (j = 0; j < n; j++)
{
printf("%s\n\n", str[j]);
}
}
return 0;
}
有用的话点个赞谢谢