zoukankan      html  css  js  c++  java
  • 字符串大小写转换(全转)(大小写互转)

    代码:
              //1. 字符串全转换大写toUpperCase()
              String str1="123abcABC哈哈,。】";
              System.out.println("字符串全转换大写前为:"+str1);
              System.out.println("字符串全转换大写toUpperCase()为:"+str1.toUpperCase());


              //2. 字符串全转换小写toLowerCase()
              String str2="123abcABC哈哈,。】";
              System.out.println("字符串全转换小写前为:"+str2);

              System.out.println("字符串全转换小写toLowerCase()为:"+str2.toLowerCase());

              //3. 字符串大小写互转

    //java包中没有自带的大小写互转的方法,所以小编自己个人写了一个方法          

                     //因为'A'的编码数值为65,而且'a'的编码数值为97

     //因为'B'的编码数值为66,而且'b'的编码数值为98
     //因为'C'的编码数值为67,而且'c'的编码数值为99
     //因为…
     //因为'Z'的编码数值为90,而且'z'的编码数值为122
     //所以大写字母对应的小写字母之间编码数值相差32.即:小写字母编码数值-大写字母编码数值=32;
     //因此,将任意一个字符串中的大写字母改为小写字母的方式为:
    String before="123abcABC哈哈,。】";//需要转换的字符串
    String after="";//用来存储转换后的字符串
    char[] split = before.toCharArray();//将字符串转为char类型字符数组

    for (int i = 0; i < split.length; i++) {
    char cc = split[i];
    if( cc < 91 && cc > 64 ){//判断如果为大写字母则进入此方法
    /*加上相差值,大写字母变为小写字母*/

    //方法1.分步转换
    int code=(int)cc;//得到
    code=code+32;
    cc=(char)code;

    //方法2.一句代码转换
    //c=(char)((int)c+32);

    }else if( cc > 96 && cc < 123){//判断如果为小写字母,则进入此方法
    /*减去相差值,小写字母变为大写字母*/

    //方法1.分步转换
    int code=(int)cc;
    code=code-32;
    cc=(char)code;

    //方法2.一句代码
    //c=(char)((int)c-32);//减去相差值,变为小写字母
    }

    //将一个个字符拼成字符串
    after+=cc;
    }
    System.out.println("字符串大小写互转前的字符串为:"+before);

    System.out.println("字符串大小写互转后的字符串为:"+after);

    打印结果:

              

  • 相关阅读:
    一个神奇的类库,可以执行字符串表达式
    Common lang一些边界方法总结(好记性不如烂笔头,需要慢慢积累).一定要利用好现有的轮子,例如Apache common与Google Guava
    借助强大的IDEA开发ide高效实现equals,hashcode以及toString方法
    数字签名是什么?
    字符串组合
    空格替换
    字符串替换 (replace)
    为什么要区分稳定和非稳定排序
    算法稳定性
    华为2018校招技术岗笔试
  • 原文地址:https://www.cnblogs.com/janesyf/p/7840975.html
Copyright © 2011-2022 走看看