当前位置:   article > 正文

在主函数中输入3个字符串,按由小到大的顺序输出_在主函数中输入3个字符串,按由小到大的顺序输出。使用指针作为参数,编写函数完成

在主函数中输入3个字符串,按由小到大的顺序输出。使用指针作为参数,编写函数完成

在主函数中输入3个字符串,按由小到大的顺序输出。使用指针作为参数,编写函数完成字符串排序功能。

  1. #include<iostream>
  2. #include<cstring>
  3. using namespace std;
  4. void sort(char *p1,char *p2);
  5. int main()
  6. {
  7. char str1[]="Hello world!";
  8. char str2[]="Tom and Jerry.";
  9. char str3[]="ABC.";
  10. cout<<"排序前:"<<endl;
  11. cout<<str1<<endl<<str2<<endl<<str3<<endl;
  12. if(strcmp(str1,str2)>0) sort(str1,str2); //比较字符串大小
  13. if(strcmp(str1,str3)>0) sort(str1,str3); //如果str1>str3,二者交换字符串,保证str1 中的字符串最小
  14. if(strcmp(str2,str3)>0) sort(str2,str3);
  15. cout<<endl;
  16. cout<<"排序后:"<<endl;
  17. cout<<str1<<endl<<str2<<endl<<str3<<endl; //输出排序后的字符串
  18. return 0;
  19. }
  20. //交换两个字符串
  21. void sort(char *p1,char *p2)
  22. {
  23. char p[20];
  24. strcpy(p,p1); //将第二个 字符串复制到第一个字符串数组中 ,将第一个字符串覆盖
  25. strcpy(p1,p2);
  26. strcpy(p2,p);
  27. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/328803?site
推荐阅读
相关标签
  

闽ICP备14008679号