Home  >  Article  >  Java  >  How to swap two strings in Java without using a third variable?

How to swap two strings in Java without using a third variable?

王林
王林forward
2023-05-06 21:49:071419browse

How to exchange two strings without using the third variable

This question is a bit interesting, right? Especially the prerequisite, do not use the third variable.

public class SwapTwoStrings {     public static void main(String[] args) {         String s1 = "沉默";         String s2 = "王二";          s1 = s1.concat(s2);         s2 = s1.substring(0,s1.length()-s2.length());         s1 = s1.substring(s2.length());          System.out.println(s1);         System.out.println(s2);     } }

The output result is as follows:

王二 沉默

Let me talk about my ideas:

1) Splice two strings together through the concat() method.

2) Then take out the second string and the first string respectively through the substring() method.

The above is the detailed content of How to swap two strings in Java without using a third variable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete