英语原文地址:https://www.javaguides.net/2020/03/java-program-to-swap-two-strings.html 作者:Ramesh Fadatare 翻译:高行行

在这篇快速文章中,我们将看到如何编写Java程序以在使用或不使用第三个变量的情况下交换两个字符串

首先,我们将看到如何编写
Java程序以使用第三个变量交换两个字符串,然后,我们将看到如何编写Java程序以不使用第三个变量交换两个字符串。

1. Java程序用第三个变量交换两个字符串

  1. package com.java.tutorials.programs;
  2. public class SwapTwoStrings {
  3. public static void main(String[] args) {
  4. String s1 = "java";
  5. String s2 = "guides";
  6. System.out.println(" before swapping two strings ");
  7. System.out.println(" s1 => " + s1);
  8. System.out.println(" s2 => " + s2);
  9. String temp;
  10. temp = s1; // java
  11. s1 = s2; // guides
  12. s2 = temp; // java
  13. System.out.println(" after swapping two strings ");
  14. System.out.println(" s1 => " + s1);
  15. System.out.println(" s2 => " + s2);
  16. }
  17. }

Output:

  1. before swapping two strings
  2. s1 => java
  3. s2 => guides
  4. after swapping two strings
  5. s1 => guides
  6. s2 => java

2. Java程序不使用第三个变量交换两个字符串

Refer the comments which are self descriptive.

  1. package com.java.tutorials.programs;
  2. /**
  3. * Java程序不使用第三个变量交换两个字符串
  4. * @author Ramesh Fadatare
  5. *
  6. */
  7. public class SwapTwoStrings {
  8. public static void main(String[] args) {
  9. String s1 = "java";
  10. String s2 = "guides";
  11. System.out.println(" before swapping two strings ");
  12. System.out.println(" s1 => " + s1);
  13. System.out.println(" s2 => " + s2);
  14. // 第一步: concat s1 + s2 and s1
  15. s1 = s1 + s2; // javaguides // 10
  16. // 第二步: 将 s1 的初始值存储到 s2 中
  17. s2 = s1.substring(0, s1.length() - s2.length()); // 0, 10-6 //java
  18. // 第三步: 将 s2 的初始值存储到 s1 中
  19. s1 = s1.substring(s2.length());
  20. System.out.println(" after swapping two strings ");
  21. System.out.println(" s1 => " + s1);
  22. System.out.println(" s2 => " + s2);
  23. }
  24. }

Output:

  1. before swapping two strings
  2. s1 => java
  3. s2 => guides
  4. after swapping two strings
  5. s1 => guides
  6. s2 => java