如何在 Java 中不使用第三個使用者定義變數交換兩個字串


我們希望在不更改任何字串的情況下交換兩個字串,即交換兩個字串的內容,我們將使用 Java 中字串類的子字串方法。首先,在對任何字串進行任何更改之前,獲取兩個字串的長度。現在,將一個字串修改為連線這兩個字串,然後將其分配給一個字串。

在此之後,使用字串類的子字串方法,使用開始索引作為新修改後的字串 1 的長度,使用最後索引作為字串 1 的初始長度。這將向我們提供已交換的字串 1,其中包含字串 2 的內容。

現在,要獲取已交換的字串 2,再次使用子字串方法,這裡使用開始索引 0 和最後索引作為字串 1 的初始長度

示例

現場演示

public class SwapString {
   public static void main(String[] args) {
      String str1 = "Ram is a good boy.";
      String str2 = "Shyam is a good man.";
      String str3 = "";
      System.out.println("string 1 : " + str1);
      System.out.println("string 2 : " + str2);
      int str1Length = str1.length();
      int str2Length = str2.length();
      str1 = str1 + str2;
      str3 = str1.substring(str1Length, str1.length());
      str2 = str1.substring(0, str1Length);
      System.out.println("string 1 : " + str3);
      System.out.println("string 2 : " + str2);
   }
}

輸出

string 1 : Ram is a good boy.
string 2 : Shyam is a good man.
string 1 : Shyam is a good man.
string 2 : Ram is a good boy.

更新時間:30-Jul-2019

231 次觀看

啟動你的 職業生涯

完成課程可獲得認證

開始
廣告
© . All rights reserved.