After sorted: 每行一个字符串
输入样例:
red yellow blue black white
After sorted: black blue red white yellow
#include<stdio.h> #include<string.h> int main() { char str[6][80]={0}; char s[80]; int i=0; for(i=0;i<5;i++) { scanf("%s",str[i]); } int j=0; for(i=0;i<4;i++)//相当于一个冒泡排序 { for(j=0;j<4-i;j++) { if(strcmp(str[j],str[j+1])>0)//比较大小,使用strcmp来比较大于0就是前一个字符串大,就要对两者进行交换 { strcpy(s,str[j]);//字符串的交换不能使用=,因为字符串名是其首元素地址,所以我们应该定义一个字符数组,使用strcpy拷贝交换 strcpy(str[j],str[j+1]); strcpy(str[j+1],s); } } } printf("After sorted:\n"); for(i=0;i<5;i++) { printf("%s\n",str[i]); } return 0; }