字符串按照字典序排序

用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;
}

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值