Java 程序中不使用第三個變量交換兩個字符串

原文地址:https://www.javaguides.net/2020/03/java-program-to-swap-two-strings.html


作者:Ramesh Fadatare


翻譯:高行行

在這篇快速文章中,我們將看到如何編寫Java程序以在使用或不使用第三個變量的情況下交換兩個字符串。

首先,我們將看到如何編寫Java程序以使用第三個變量交換兩個字符串,然後,我們將看到如何編寫Java程序以不使用第三個變量交換兩個字符串。

1. Java程序用第三個變量交換兩個字符串

<code>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);
}
}/<code>

Output:

<code> before swapping two strings 
s1 => java
s2 => guides
after swapping two strings
s1 => guides
s2 => java/<code>


2. Java程序不使用第三個變量交換兩個字符串

Refer the comments which are self descriptive.

<code>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);
}
}/<code>

Output:

<code> before swapping two strings 
s1 => java
s2 => guides
after swapping two strings
s1 => guides
s2 => java/<code>


分享到:


相關文章: