OpenJudge NOI 1.7 16:忽略大小写的字符串比较

【题目链接】

OpenJudge NOI 1.7 16:忽略大小写的字符串比较

【题目考点】

1. 字符串
2. 大小写转换

'a’的ASCII码是97,'A’的ASCII码是65,同一字母的大小写字母的ASCII码差值为32。小写转大写:减32;大写转小写:加32。

【题解代码】

解法1:将字符串中的字母都转为小写字母,而后比较

类似方法:都转为大写字母后再比较

#include <bits/stdc++.h>
using namespace std;
int main()
{
    char s1[85], s2[85];
    cin.getline(s1, 85);
    cin.getline(s2, 85);
    int l1 = strlen(s1), l2 = strlen(s2);
    for(int i = 0; i < l1; ++i)//将字符串中大写字母都转为小写字母
    {
        if(s1[i] >= 'A' && s1[i] <= 'Z')
            s1[i] += 32;
    }
    for(int i = 0; i < l1; ++i)//将字符串中大写字母都转为小写字母
    {
        if(s2[i] >= 'A' && s2[i] <= 'Z')
            s2[i] += 32;
    }
    int cmp = strcmp(s1, s2);
    if(cmp < 0)
        cout << '<';
    else if(cmp > 0)
        cout << '>';
    else
        cout << '=';
    return 0;
}
解法2:自己实现不区分大小写的Strcmp函数

将字母转为序号 A或a转为0, B或b转为1,。。。Z或z为25,而后比较。

#include <bits/stdc++.h>
using namespace std;
int Strcmp(char s1[], char s2[])//不区分大小写比较两个字符串
{
    int l1 = strlen(s1), l2 = strlen(s2), n1, n2;//n1,n2:s1与s2某字符的字母编号 
    for(int i = 0; i < l1 && i < l2; ++i)
    {
        if(isalpha(s1[i]) && isalpha(s2[i]))//如果都是字母
        {
            n1 = s1[i] - (islower(s1[i]) ? 'a' : 'A');
            n2 = s2[i] - (islower(s2[i]) ? 'a' : 'A');
            if(n1 > n2)
                return 1;
            else if(n1 < n2)
                return -1;
        }
        else
        {
            if(s1[i] > s2[i])
                return 1;
            else if(s1[i] < s2[i])
                return -1;
        }
    }
    if(l1 > l2)
        return 1;
    else if(l1 < l2)
        return -1;
    else
        return 0;
} 
int main()
{
    char s1[85], s2[85];
    cin.getline(s1, 85);
    cin.getline(s2, 85);
    int ans = Strcmp(s1, s2);
    if(ans > 0)
        cout << '>';
    else if(ans < 0)
        cout << '<';
    else
        cout << '=';
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值