赞
踩
在主函数中输入3个字符串,按由小到大的顺序输出。使用指针作为参数,编写函数完成字符串排序功能。
- #include<iostream>
- #include<cstring>
- using namespace std;
- void sort(char *p1,char *p2);
- int main()
- {
- char str1[]="Hello world!";
- char str2[]="Tom and Jerry.";
- char str3[]="ABC.";
- cout<<"排序前:"<<endl;
- cout<<str1<<endl<<str2<<endl<<str3<<endl;
- if(strcmp(str1,str2)>0) sort(str1,str2); //比较字符串大小
- if(strcmp(str1,str3)>0) sort(str1,str3); //如果str1>str3,二者交换字符串,保证str1 中的字符串最小
- if(strcmp(str2,str3)>0) sort(str2,str3);
- cout<<endl;
- cout<<"排序后:"<<endl;
- cout<<str1<<endl<<str2<<endl<<str3<<endl; //输出排序后的字符串
- return 0;
- }
- //交换两个字符串
- void sort(char *p1,char *p2)
- {
- char p[20];
- strcpy(p,p1); //将第二个 字符串复制到第一个字符串数组中 ,将第一个字符串覆盖
- strcpy(p1,p2);
- strcpy(p2,p);
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。