翻转字符串里面的单词

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

示例:

输入: "the sky is blue".
输出: "blue is sky the".

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
题目分析:

将字符串里面的单词翻转,并去除多余的空格;可以使用split()函数将字符串中的字符按空格“ ”分隔,然后从字符串的尾部开始将一个个单词加入新字符串中,并在每个单词之间加入空格。

代码实现:
public String reverseWords(String s) {
   if (s == null || s.length() == 0)
       return "";

   String[] string = s.split(" ");
   String res = "";

   for (int i = string.length - 1; i >= 0; i--) {
       if (!string[i].equals("")){
           if (res.length() > 0){
               res += " ";
           }
           res += string[i];
       }
   }

   return res;
}
主函数:
public static void main(String[] args) {
   S2 s = new S2();
   String string = "the sky is blue";
   String res = s.reverseWords(string);
   System.out.println(res);
}
运行结果:

blue is sky the

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值