输入三个字符串,按照从小到大的顺序输出(c++)

来源:百度知道 编辑:UC知道 时间:2024/05/29 08:01:46

void main()
{
char st[20],cs[3][20];
int i,j,p;
printf("input three string:\n");
for(i=0;i<3;i++)
gets(cs[i]);
printf("\n");
for(i=0;i<3;i++)
{
p=i;strcpy(st,cs[i]);
for(j=i+1;j<3;j++)
if(strcmp(cs[j],st)<0)
{
p=j;
strcpy(st,cs[j]);
}
if(p!=i)
{
strcpy(st,cs[i]);
strcpy(cs[i],cs[p]);
strcpy(cs[p],st);
}
puts(cs[i]);
}
printf("\n");
getch();
}
这是最基本的方法,当用字符串比较函数strcpy时,需要去交换3个字符串,你也可以用指针做,去交换地址,效率会比这个高。

函数名: strncmp
功 能: 串比较
用 法: int strncmp(char *str1, char *str2, int maxlen);
说明:比较字符串str1和str2的大小,如果str1小于str2,n就<0,反之如果str1大于str2,n就>0,如果str1等于str2,n就=0

用了STL中的vector、sort()函数、iterator

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include&