P291 2.输入3个字符串,按由小到大的顺序输出(使用指针)
注意:1.字符串比较大小使用strcmp(str1,str3),不能写成str1 > str3
2.一个字符串赋值给另一个字符串要用strcpy(p4,p1),不能写成“p4=p1”
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main() {
void sswap(char* str1, char* str2);
char str1[20] = { 0 }, str2[20] = { 0 }, str3[20] = { 0 };
printf("请输入3个字符串:\n");
gets(str1);
gets(str2);
gets(str3);
//字符串比较大小使用strcmp(),不能写成str1 > str3
if (strcmp(str1,str2)>0) sswap(str1, str2);
if (strcmp(str1,str3)>0) sswap(str1, str3);
if (strcmp(str2,str3)>0) sswap(str2, str3);
printf("由小到大的顺序为:\n%s\n%s\n%s\n", str1, str2, str3);
return 0;
}
void sswap(char* p1, char* p2) {
//一个字符串赋值给另一个字符串要用strcpy(p4, p1), 不能写成“p4 = p1”
char p4[20] = { 0 };
strcpy(p4, p1);
strcpy(p1, p2);
strcpy(p2, p4);
}
运行结果: