Home> Java> javaTutorial> body text

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

王林
Release: 2023-05-06 21:49:07
forward
1359 people have browsed it

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); } }
Copy after login

The output result is as follows:

王二 沉默
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!