如何在不使用第三個變數的情況下在 Java 中交換兩個字串?


無需第三個內容交換兩個字串(假定為 s1 和 s2)的內容。

  • 首先使用連線運算子“+”連線給定的兩個字串,並存儲在 s1(第一個字串)中。

s1 = s1+s2;
  • String 類的子字串方法用於此方法具有兩個變數,並返回一個作為此字串的子字串的新字串。此子字串從指定索引處的字元開始,並一直擴充套件到此字串的末尾,或在給出第二個引數時直到 endIndex - 1。

    現在使用 String 類的substring() 方法在 s2 中儲存 s1 的值,反之亦然。

s2 = s1.substring(0,i);
s1 = s1.substring(i);

例如

即時演示

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 年 7 月 30 日

1 千多個檢視次數

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.