当前位置:首页 > 技术杂谈 > 正文

给定一个字符串,逐个翻转字符串中的每个单词

2024-03-31 技术杂谈

示例:

输入:
"the sky is blue",

输出:
"blue is sky the".

 public  String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        if(s == null || "".equals(s.trim())){
            return "";
        }else{
            String [] strs = s.trim().split("\s ");
            int len = strs.length-1;
            for(int i=len;i>=0;i--){
                if(i == 0){
                    sb.append(strs[i]);
                }else{
                    sb.append(strs[i] " ");
                }
            }
            return sb.toString();
        }
    }

trim()去除字符串两头空格,split()的用法

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/a/17044.html