合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。💪🏻
一、题目描述 ⭐️
习题8-7 字符串排序
本题要求编写程序,读入5个字符串,按由小到大的顺序输出。
输入格式:
输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。
输出格式:
按照以下格式输出排序后的结果:
After sorted:
每行一个字符串
输入样例:
red yellow blue black white
输出样例:
After sorted:
black
blue
red
white
yellow
二、代码(C语言)⭐️
#include <stdio.h> // 包含标准输入输出库,用于使用输入输出函数(如 scanf 和 printf)
#include <string.h> // 包含字符串处理函数库,用于使用字符串相关函数(如 strcmp 和 strcpy)
int main() {
char strs[5][82]; // 定义二维字符数组 strs,用于存储 5 个字符串,每个字符串最多 81 个字符
// 输入 5 个字符串
for (int i = 0; i < 5; i++) { // 外层循环,遍历 5 个字符串
scanf("%s", strs[i]); // 输入第 i 个字符串
}
// 使用冒泡排序对字符串进行排序
for (int i = 0; i < 5; i++) { // 外层循环,遍历每个字符串
for (int j = i + 1; j < 5; j++) { // 内层循环,从 i+1 开始遍历剩余字符串
if (strcmp(strs[i], strs[j]) > 0) { // 如果 strs[i] 大于 strs[j]
char temp[82]; // 定义临时字符数组 temp,用于交换字符串
strcpy(temp, strs[j]); // 将 strs[j] 复制到 temp
strcpy(strs[j], strs[i]); // 将 strs[i] 复制到 strs[j]
strcpy(strs[i], temp); // 将 temp 复制到 strs[i]
}
}
}
// 输出排序后的字符串
printf("After sorted:\n"); // 输出提示信息
for (int i = 0; i < 5; i++) { // 遍历排序后的字符串
printf("%s\n", strs[i]); // 输出第 i 个字符串
}
return 0; // 程序正常结束
}
三、知识点 ⭐️
1
、scanf中,遇到%s,不加&;
2
、比较字符串大小用strcmp;
3
、复制字符串用strcpy;