如何在沒有第三個變數的情況下交換兩個字串變數。


若要在沒有第三者的情況下交換兩個字串(假定為 s1 和 s2)的內容,首先將它們連線起來並存儲在 s1 中。現在使用字串類的 substring() 方法將 s1 的值儲存在 s2 中,反之亦然。

舉例說明

 線上演示

public class Sample {
   public static void main(String args[]){
      String s1 = "tutorials";
      String s2 = "point";
      System.out.println("Value of s1 before swapping :"+s1);
      System.out.println("Value of s2 before swapping :"+s2);
      int i = s1.length();
      s1 = s1+s2;
      s2 = s1.substring(0,i);
      s1 = s1.substring(i);
      System.out.println("Value of s1 after swapping :"+s1);
      System.out.println("Value of s2 after swapping :"+s2);
   }
}

輸出

Value of s1 before swapping :tutorials
Value of s2 before swapping :point
Value of s1 after swapping :point
Value of s2 after swapping :tutorials

更新時間: 2019-07-30

3K+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告