保留空格位置反轉給定字串的 Java 程式。


可以使用 StringBuffer 類中的 reverse() 方法來反轉給定字串的內容,同時保留空格。

示例

public class Test {
   public static void main(String args[]) {
      String str = "hi welcome to Tutorialspoint";
      String strArray[] = str.split(" ");
      StringBuffer sb= new StringBuffer(str);
      sb.reverse();
      for(int i=0 ; i<str.length(); i++){
      if(str.charAt(i)== ' '){
         sb.insert(i, " ");
      }
   }
   sb.append("");
   System.out.println(sb);
}

輸出

tn iopslai ro tuT ot emoclew ih

更新於:2020 年 2 月 26 日

4K+瀏覽次數

開啟您的 職業生涯

完成課程,獲得認證

開始
Advertisement