c++中的字符串大小排序

#include<iostream>
#include<string>
#include <cstring>
using namespace std;
void sort(string a[],int n);
int main()
{	int size=0;
	bool flag=true;
	while(flag)
	{
		cout<<"请输入要对比的字符串个数(0~100):";
		cin>>size;
		if(size>0&&size<=100)
		{
			flag=false;
		}
		else
		{
			cout<<"输入的个数不正确"<<endl;
		}
	}
	string *p=new string[size];
	for(int i=0;i<size;i++)
	{	
	 	cin.sync();
	 	cout<<"请输入第"<<i+1<<"个字符串:"; 
		getline(cin,p[i],'\n');
	}
	cout<<"\n\n\n";
	sort(p,size);
	cout<<"排序后的字符串"<<endl;
	for(int n=0;n<size;n++)
	{
		cout<<"N0."<<n+1<<"的字符串:";
		cout<<p[n]<<endl;
	}
	delete p;
	return 0;
}
void sort(string a[],int n)//从大到小 
{
int i,j;
string t;
for(i=0;i<n-1;i++)
{
    for(j=0;j<n-i-1;j++)
    {
        if(strlen(a[j].c_str())<strlen(a[j+1].c_str()))//这里是吧string转化为char类型去比较,这样做更好
        {
			t=a[j];
			a[j]=a[j+1];
			a[j+1]=t;
        }
	}
}
}
/*
测试用的字符串 
An old woman had a cat
Do not hit your old servant
The Old Cat
aoo
*/
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值