描述
You have a lot of photos whose file names are like:
beijing1
beijing10
beijing8
shanghai233
As you can see, all names have exactly two parts: the string part and the number part. If you sort the files in lexicographical order "beijing10" will go before "beijing8". You do not like that. You want to sort the files first in lexicographical order of the string part then in ascending order of the number part. Can you write a program to work it out?
输入
The first line contains an integer N denoting the number of files. (1 <= N <= 100)
The following N lines each contain a file name as described above.
It is guaranteed that the number part has no leading zeroes and is no more than 1000000.
输出
The sorted files one per line.
样例输入
4 beijing1 beijing10 beijing8 b233
样例输出
b233 beijing1 beijing8 beijing10
解题:字符串处理
#include<bits/stdc++.h>
using namespace std;
struct PhotoName{
string str;
int num;
}p[101];
void CreatePhotoName(int i,string s)
{
int k,n=0;
int L=s.size();
for(k=0;k<L;k++)
{
if(s[k]>='0' && s[k]<='9')
break;
}
string s1=s.substr(0,k);
for(int j=k;j<L;j++)
{
n=n*10+s[j]-'0';
}
p[i].str = s1;
p[i].num = n;
return;
}
bool cmpPhotoName(PhotoName p,PhotoName q)
{
if( p.str == q.str )
return p.num<q.num;
else
return p.str<q.str;
}
int main()
{
string s;
int i,N;
cin>>N;
for(i=0;i<N;i++)
{
cin>>s;
CreatePhotoName(i,s);
}
sort(p,p+N,cmpPhotoName);
for(i=0;i<N;i++)
{
cout<<p[i].str<<p[i].num<<endl;
}
return 0;
}