反轉 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+ 瀏覽量

開啟你的職業生涯

完成本課程即可獲得認證

立即開始
廣告