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


若要交換兩個字串(假設為 s1 和 s2)的內容,而沒有第三個變數,首先將它們連線起來並存儲在 s1 中。現在使用 String 類 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

更新於:30-7-2019

3K+ 瀏覽次數

開啟你的 事業

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.