A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 刘文秀 中级黑马   /  2016-7-30 21:33  /  410 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

将"goOd gooD stUdy dAy dAy up"每个单词的首字母转换成大写其余还是小写字母(不许直接输出good good study day day up 要用代码实现)

3 个回复

倒序浏览
package com.itheima;

public class Demo2 {
        /*将"goOd gooD stUdy dAy dAy up"
    每个单词的首字母转换成大写其余还是小写字母
    (不许直接输出good good study day day up 要用代码实现)*/
        public static void main(String[] args) {
                String str = "goOd gooD stUdy dAy dAy up";
                //使用空格切割字符串,把切割出来的字符串放到集合中
                String[] arr = str.split(" ");
                //循环字符串数组
                for(int i =0;i<arr.length;i++){
                        //遍历集合中的元素的字符
                        for(int j =0;j<arr[i].length();j++){
                                //判断数组中的元素的第一个字符,直接把第一个字符调用touppercase方法大写
                                if(j==0){
                                        System.out.print((arr[i].charAt(j)+"").toUpperCase());
                                //如果不是第一个字符,则调用转换小写方法
                                }else{
                                        System.out.print((arr[i].charAt(j)+"").toLowerCase());
                                }
                        }
                        //使每一个数组中的字符串元素用空格隔开,输出美观
                        System.out.print("  ");
                }
        }
}

刚写好  奉上
回复 使用道具 举报
cat73 黑马帝 2016-7-31 09:25:26
藤椅
[Java] 纯文本查看 复制代码
        String str = "goOd gooD stUdy dAy dAy up";

        Matcher m = Pattern.compile("(^| )([a-z])([a-zA-Z]*)").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
           m.appendReplacement(sb, "$1" + m.group(2).toUpperCase() + "$3");
        }
        
        System.out.println(sb);

输出:
[Java] 纯文本查看 复制代码
GoOd GooD StUdy DAy DAy Up
回复 使用道具 举报
66666666666666666666666666666
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马