C 练习实例79
题目:字符串排序。
程序分析:无。
程序源代码:
实例
// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鸟教程. All rights reserved.
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
void swap(char*str1,char*str2);
int main()
{
char str1[20],str2[20],str3[20];
printf("请输入3个字符串,每个字符串以回车结束!:\n");
fgets(str1, (sizeof str1 / sizeof str1[0]), stdin);
fgets(str2, (sizeof str2 / sizeof str2[0]), stdin);
fgets(str3, (sizeof str3 / sizeof str3[0]), stdin);
if(strcmp(str1,str2)>0)swap(str1,str2);
if(strcmp(str2,str3)>0)swap(str2,str3);
if(strcmp(str1,str2)>0)swap(str1,str2);
printf("排序后的结果为:\n");
printf("%s\n%s\n%s\n",str1,str2,str3);
return 0;
}
void swap(char*str1,char*str2)
{
char tem[20];
strcpy(tem,str1);
strcpy(str1,str2);
strcpy(str2,tem);
}
以上实例运行输出结果为:
请输入3个字符串,每个字符串以回车结束!: b a t 排序后的结果为: a b t
C 语言经典100例
德林恩宝零零
319***5092@qq.com
参考方法:
#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int n,len,i,j,maxloc; char ptr[1000],*p; printf("请输入整数(字符串长度):\n"); scanf("%d",&n); getchar(); char *str[n]; printf("请输入字符,每个字符以回车结束!:\n"); for(i=0;i<=n-1;i++) { fgets(ptr, (sizeof ptr / sizeof ptr[0]), stdin); len=strlen(ptr); str[i]=(char*)malloc(sizeof(char)*(len+1)); strcpy(str[i],ptr); } printf("字符串排序后:\n"); for(i=0;i<=n-1;i++) { maxloc=i; for(j=i+1;j<=n-1;j++) { if(strcmp(str[j],str[maxloc])<0) maxloc=j; } if(maxloc!=i) { p=str[maxloc]; str[maxloc]=str[i]; str[i]=p; } } for(i=0;i<=n-1;i++) printf("%s\n",str[i]); return 0; }德林恩宝零零
319***5092@qq.com