HOJ 1081 Scramble Sort

本文介绍了一种字符串处理方法,包括忽略大小写排序、数字转换与排序等细节。使用自定义排序函数strsort处理字符串数组,并通过atoi函数处理数字字符串。文章还详细说明了输出格式的要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串处理。。题目就不介绍了。应该是一道比较水的题,思路很简单,就是排个序。

但是有很多细节要注意,也很考验一些基本功。

1.注意字母排序时是不区分大小写的。本来想用现成的sort,但是处理二维数组,并且还要忽略大小写,本弱菜不知道该怎么写了。最后放弃sort,自己写了一个对字符串进行排序的strsort。最朴素的n^2的排序。。还好最后没超时。

2.对于数字,可以用atoi这个函数。

atoi()会扫描参数nptr字符串,检测到第一个数字或正负符号时开始做类型转换,之后检测到非数字或结束符 \0 时停止转换,返回整型数。

然后直接sort即可。

3.我用了一个bool types[]记录哪个位置应该出数字还是单词

4.注意输出的时候逗号,句号及空格的安排。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
#include <memory.h>

using namespace std;
char str0[105][100];
int str1[105];
bool types[205];
int l0;
int num0,num1;

bool cmp0(char a[],char b[])
{
    int i;
    for(i=0; i<strlen(a); i++)
        if(a[i]>='A'&&a[i]<='Z') a[i]=a[i]+32;
    for(i=0; i<strlen(b); i++)
        if(b[i]>='A'&&b[i]<='Z') b[i]=b[i]+32;
    if(strcmp(a,b)>0) return 1;
    else return 0;
}
void strsort()
{
    int i,j;
    for(i=0;i<num0;i++)
        for(j=0;j<num0;j++)
        {
            char b1[1000],b2[1000];
            strcpy(b1,str0[i]);
            strcpy(b2,str0[j]);
            if(!cmp0(b1,b2))
            {
                char t[1000];
                strcpy(t,str0[i]);
                strcpy(str0[i],str0[j]);
                strcpy(str0[j],t);
            }
        }
}
int main()
{
    while(1)
    {
        num0=0;
        num1=0;
        memset(types,0,sizeof(types));
        char temp[100];
        int i=0;
        while(1)
        {
            scanf("%s",temp);

            if((temp[0]>='0'&&temp[0]<='9')||temp[0]=='-') //注意负数的情况
            {
                types[i]=1;
                str1[num1++]=atoi(temp);
            }
            else
            {
                types[i]=0;
                strcpy(str0[num0++],temp);
            }
            i++;
            int l=strlen(temp);
            if((temp[l-1])=='.')break;
        }
        if(strcmp(temp,".")==0)break;
        strsort();
        sort(str1,str1+num1);
        int counter0=0;
        int counter1=0;
        for(int i=0;; i++)
        {
            if(types[i]==0)
            {
                if(counter0==num0)continue;
                str0[counter0][strlen(str0[counter0])-1]='\0'; //把单词最后的那个逗号给去掉
                printf("%s",str0[counter0++]);
            }
            else
            {
                if(counter1==num1)continue;
                printf("%d",str1[counter1++]);
            }
            if(counter0==num0&&counter1==num1)
            {
                printf(".\n");
                break;
            }
            printf(", ");
        }
    }
    return 0;
}


转载于:https://www.cnblogs.com/MicZ/archive/2012/09/03/2785370.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值