JavaSE基础 多个字符串首字母大写其他字母小写的三种写法

本文介绍多种首字母大写,其他字母小写的方法

要求如下:

将字符串"goOd gooD stUdy dAy dAy up"每个单词的首字母转换成大写其余字母小写

第一种写法

  • 这种写法,主要为substring(), toUpperCase() 主要思想为截取和拼接
  public class Test01 {
        public static void main(String[] args) {
        String s = "goOd gooD stUdy dAy dAy up";

        //将原字符串按照空格切割,返回一个字符数组
        String[] split = s.split(" ");

        StringBuffer sb = new StringBuffer();

        //遍历字符串数组 ,第一种方法,将第一个字母和后面的字母用substring分割,再用toUpperCase()变为大写
        for (int i = 0; i < split.length; i++) {

            //将每次遍历的字符串用substring(0, 1)截取首字母,转为大写. substring(1,split[i].length())截取后面的字母, 转为小写,再拼接
            String ss = split[i].substring(0, 1).toUpperCase()+split[i].substring(1).toLowerCase();

            //StringBuffer拼接字符串
            sb.append(ss);

            //给字符串中添加空格
            sb.append(" ");
        }
                //输出结果
        System.out.println(sb.toString());

    }
}

第二种写法

  • 这种写法的主要思想为把大写字母的字符单独拿出来,把字符变大写,用的是ch[0]-=32,和Character的toUpperCase()静态方法
public class Test01 {
    public static void main(String[] args) {

       String s = "goOd gooD stUdy dAy dAy up";

        //先将字符串全部变为小写
        s = s.toLowerCase();

        //将原字符串按照空格切割,返回一个字符数组
        String[] split = s.split(" ");

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < split.length; i++) {
            //将字符串转为字符数组
            char[] ch = split[i].toCharArray();

            //使用ASCII表中的小写字母-32即为大写
            //ch[0]-=32;

            //ch[0]-=32; 可读性较差,直接用Character的包装类,来把字符转为大写
            ch[0] = Character.toUpperCase(ch[0]);

            //使String的构造方法新建一个匿名字符串
            sb.append(new String(ch));
            sb.append(" ");
        }

        //输出结果
        System.out.println(sb.toString());

    }
}

第三种写法

  • 本方法的主要思想为,使用replace方法,将首字母替换为大写字母. String中,replace(s1, s2)的用法为,将s1,替换为s2
public class Test01 {
    public static void main(String[] args) {
        String s = "goOd gooD stUdy dAy dAy up";

        //先将字符串全部变为小写
        s = s.toLowerCase();

        //将原字符串按照空格切割,返回一个字符数组
        String[] split = s.split(" ");

        StringBuffer sb = new StringBuffer();       

        for (int i = 0; i < split.length; i++) {

            //使用字符串的replace方法
            //split[i].substring(0, 1)表示需要替换的首字母
            //split[i].substring(0, 1).toUpperCase())表示替换上的大写首字母
            String str = split[i].replace(split[i].substring(0, 1), split[i].substring(0, 1).toUpperCase());

            //StringBuffer拼接字符串
            sb.append(str);
            sb.append(" ");

        }

        //输出结果
        System.out.println(sb.toString());

    }
}

三种写法的运行结果如下图所示:

  • 总结: 三种方法,分别用了:
  • substring(), toUpperCase()的方法
  • ch[0]-=32;ASCII码值减去32 的方法,Character的toUpperCase()静态方法
  • 字符串的replace(s1, s2)方法 

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/79323839
今日推荐