大小写字母的转化

方法1:利用toLowerCase()将字符串转化为小写,toUpperCase()将字符串转化为大写。
注意:转化过程并不是对原字符串s进行转化,而是需要形成新的字符串存到S中。

 Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        System.out.println("原字符串:"+s);
        String S = s.toUpperCase();
        System.out.println("转化为大写字母:"+S);
        System.out.println("此时s没有变化:"+s);
        System.out.println("大写字母"+S+"转变为小写字母"+S.toLowerCase());

z
方法2(强制转化)
实际上是先判断是大写字母还是小写字母,然后再进行ascii值的转化,如果是大写字母想要转换为小写字母,则将原字符加上32再强制转换为char型,同理,如果是小写字母转化为大写字母则要将字符减去32,再转化为char型。
补充:大写字母A-Z的ascii值为65-90,小写字母a-z的ascii值为97-122。

public class Main {
    public static void main(String[] args) {
        char c = 'a';
        char c2 = 0;
        if('a'<= c && c <= 'z'){
             c2 = lowerToSupper(c);
            System.out.println("小写字符为" + c + " 大写字符为"+ c2);
        }
        if('A' <= c2 && c2 <= 'Z'){
            char c3 = upperToLower(c2);
            System.out.println("大写字符为" + c2 + " 小写字符为"+ c3);
        }
    }
    public static char upperToLower(char c){
        return (char)(c + 32);
    }
    public static char lowerToSupper(char c){
        return (char)(c - 32);
    }
}

需要注意的是在用ascii码加的时候需要加32而不是26。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值