如何在不使用第三个变量的情况下在 Java 中交换两个字符串变量 [英] How to swap two string variables in Java without using a third variable

查看:21
本文介绍了如何在不使用第三个变量的情况下在 Java 中交换两个字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中交换两个字符串变量而不使用第三个变量,即临时变量?

How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;

但是这里还有第三个变量.我们需要消除第三个变量的使用.

But here there is a third variable. We need to eliminate the use of the third variable.

推荐答案

在不使用第三个变量的情况下这样做:

Do it like this without using a third variable:

String a = "one";
String b = "two";

a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());

System.out.println("a = " + a);
System.out.println("b = " + b);

这篇关于如何在不使用第三个变量的情况下在 Java 中交换两个字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆