用sort()函数对字符串进行字典序排序
定义结构体存储字符串
struct node
{
char st[1000];
}a[100000];
定义排序规则
字典序
bool cmp(node s1,node s2)
{
return strcmp(s1.st,s2.st)<0;
}
降序
bool cmp1(node s1,node s2)
{
return strcmp(s1.st,s2.st)>0;
}
完整代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
char st[1000];
}a[100000];
bool cmp(node s1,node s2)
{
return strcmp(s1.st,s2.st)<0;
}
bool cmp1(node s1,node s2)
{
return strcmp(s1.st,s2.st)>0;
}
int main()
{
int n;
while(scanf("%d",&n)){
for(int i=0;i<n;i++){
scanf("%s",a[i].st);
}
sort(a,a+n,cmp);
for(int i=0;i<n;i++) printf("%s\n",a[i].st);
cout<<"---------------"<<endl;
sort(a,a+n,cmp1);
for(int i=0;i<n;i++) printf("%s\n",a[i].st);
}
return 0;
}
其他方法
按照字典序从小到大排序
void sort(int n)
{
char temp[100];
for(int i=0;i<n-1;i++){
for(int j=0;j<n-1-i;j++){
if(strcmp(st[j],st[j+1])>0){
strcpy(temp,st[j]);
strcpy(st[j],st[j+1]);
strcpy(st[j+1],temp);
}
}
}
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char st[100][100];
void sort(int n)
{
char temp[100];
for(int i=0;i<n-1;i++){
for(int j=0;j<n-1-i;j++){
if(strcmp(st[j],st[j+1])>0){
strcpy(temp,st[j]);
strcpy(st[j],st[j+1]);
strcpy(st[j+1],temp);
}
}
}
}
int main()
{
int n;
while(scanf("%d",&n)==1){
for(int i=0;i<n;i++){
scanf("%s",st[i]);
}
sort(n);
for(int i=0;i<n;i++){
puts(st[i]);
}
}
return 0;
}