#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
*/
c++中的字符串大小排序
最新推荐文章于 2024-05-19 21:39:33 发布