反转 Java 中给定的字符串中的单词


字符串中单词的顺序可以被反转并且字符串以单词反序的形式显示。如下所示提供一个该功能的示例。

String = I love mangoes
Reversed string = mangoes love I

如下所示提供一个用于展示该功能的程序。

示例

 实际演示

import java.util.regex.Pattern;
public class Example {
   public static void main(String[] args) {
      String str = "the sky is blue";
      Pattern p = Pattern.compile("\s");
      System.out.println("The original string is: " + str);
      String[] temp = p.split(str);
      String rev = "";
      for (int i = 0; i < temp.length; i++) {
         if (i == temp.length - 1)
         rev = temp[i] + rev;
         else
         rev = " " + temp[i] + rev;
      }
      System.out.println("The reversed string is: " + rev);
   }
}

输出

The original string is: the sky is blue
The reversed string is: blue is sky the

现在让我们了解一下上述程序。

首先打印原始字符串。然后当存在空格字符时字符串被拆分并存储在数组 temp 中。如下所示提供展示该功能的代码片段。

String str = "the sky is blue";
Pattern p = Pattern.compile("\s");
System.out.println("The original string is: " + str);
String[] temp = p.split(str);
String rev = "";

然后通过迭代字符串 temp,使用 for 循环以反序将字符串存储在字符串 rev 中。最后显示 rev。如下所示提供展示该功能的代码片段 −

for (int i = 0; i < temp.length; i++) {
   if (i == temp.length - 1)
   rev = temp[i] + rev;
   else
   rev = " " + temp[i] + rev;
}
System.out.println("The reversed string is: " + rev);

更新于: 25-6 月 -2020

5000+ 浏览量

开启你的职业生涯

完成本课程即可获得认证

立即开始
广告
© . All rights reserved.