c++字符串排序

  在主函数中输入10个等长的字符串,用另一函数对它们排序。然后在主函数输出这10个已排好序的字符串。
  
  用两种方法完成。
  
  方法一:用二维数组做函数参数;
  
  方法二:用指向一维数组的指针做函数参数。
  
  方法一:二维数组:
  
  #include<iostream>
  
  #include<string.h>
  
  using namespace std;
  
  int main()
  
  {
  
  char str[10][20];
  
  cout<<"input 10 strings in the same length:"<<endl;
  
  for(int i=0;i<10;i++)cin>>str[i];
  
  void sort(char [10][20]);
  
  sort(str);
  
  cout<<"now the sorted strings are:"<<endl;
  
  void print(char [10][20]);
  
  print(str);
  
  return 0;
  
  }
  
  void sort(char a[10][20])
  
  {
  
  for(int i=0;i<10;i++)
  
  {int k=i;char t[20];
  
  for(int j=i;j<10;j++)
  
  if(strcmp(a[j],a[k])<0)
  
  {
  
  strcpy(t,a[j]);strcpy(a[j],a[k]);strcpy(a[k],t);
  
  }
  
  }
  
  }
  
  void print(char a[10][20])
  
  {
  
  for(int j=0;j<10;j++)cout<<a[j]<<endl;
  
  }
  
  运行结果:
  
  方法二:用指向一维数组的指针做函数参数:
  
  #include<iostream>
  
  #include<string.h>
  
  using namespace std;
  
  int main()
  
  {
  
  char (*p)[10];char ch[10][10];
  
  cout<<"input 10 strings:"<<endl;
  
  for(int i=0;i<10www.furongpt.com;i++)cin>>ch[i];
  
  p=ch;
  
  void sort(char (*)[10]);
  
  sort(p);
  
  cout<<"now the strings are:"<<endl;
  
  for(int j=0;j<10;j++)cout<<p[j]<<endl;
  
  return 0;
  
  }
  
  void sort(char www.furong157.com (*p)[10])
  
  {
  
  for(int i=0;i<10;i++)
  
  {int k=i;char t[10];
  
  for(int j=i;j<10;j++)
  
  if(strcmp(p[j],p[k])www.567860.cn <0)
  
  {
  
  strcpy(t,p[j]);strcpy(p[j],p[k]);strcpy(p[k],t);
  
  }

转载于:https://www.cnblogs.com/qwangxiao/p/8647403.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值