Do not use a third variable exchange two strings in Java programs

English Original Address: https://www.javaguides.net/2020/03/java-program-to-swap-two-strings.html

Author: Ramesh Fadatare

Translation: the high trekking

In this quick article, we will see how to write a Java program in exchange for two strings in the case with or without a third variable .

First, we will see how to write a Java program to use a third variable exchange two strings , then we will see how to write Java programs without using a third variable exchange two strings.

1. Java program exchange two strings with a third variable

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 programs do not use a third variable exchange two strings

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

Guess you like

Origin www.cnblogs.com/gaohanghang/p/12521688.html