英语原文地址:https://www.javaguides.net/2020/03/java-program-to-swap-two-strings.html
翻译:高行行
在这篇快速文章中,我们将看到如何编写Java程序以在使用或不使用第三个变量的情况下交换两个字符串。
首先,我们将看到如何编写Java程序以使用第三个变量交换两个字符串,然后,我们将看到如何编写Java程序以不使用第三个变量交换两个字符串。
1. Java程序用第三个变量交换两个字符串
package com.java.tutorials.programs;
public class SwapTwoStrings {
public static void main(String[] args) {
String s1 = "java";
String s2 = "guides";
System.out.println(" before swapping two strings ");
System.out.println(" s1 => " + s1);
System.out.println(" s2 => " + s2);
String temp;
temp = s1; // java
s1 = s2; // guides
s2 = temp; // java
System.out.println(" after swapping two strings ");
System.out.println(" s1 => " + s1);
System.out.println(" s2 => " + s2);
}
}
Output:
before swapping two strings
s1 => java
s2 => guides
after swapping two strings
s1 => guides
s2 => java
2. Java程序不使用第三个变量交换两个字符串
Refer the comments which are self descriptive.
package com.java.tutorials.programs;
/**
* Java程序不使用第三个变量交换两个字符串
* @author Ramesh Fadatare
*
*/
public class SwapTwoStrings {
public static void main(String[] args) {
String s1 = "java";
String s2 = "guides";
System.out.println(" before swapping two strings ");
System.out.println(" s1 => " + s1);
System.out.println(" s2 => " + s2);
// 第一步: concat s1 + s2 and s1
s1 = s1 + s2; // javaguides // 10
// 第二步: 将 s1 的初始值存储到 s2 中
s2 = s1.substring(0, s1.length() - s2.length()); // 0, 10-6 //java
// 第三步: 将 s2 的初始值存储到 s1 中
s1 = s1.substring(s2.length());
System.out.println(" after swapping two strings ");
System.out.println(" s1 => " + s1);
System.out.println(" s2 => " + s2);
}
}
Output:
before swapping two strings
s1 => java
s2 => guides
after swapping two strings
s1 => guides
s2 => java