如何在 Java 中不使用第三个变量来交换两个字符串?
java 8object oriented programmingprogramming更新于 2025/9/18 16:44:17
不使用第三个变量来交换两个字符串(例如 s1 和 s2)的内容。
首先使用连接运算符"+"连接给定的两个字符串并存储在 s1(第一个字符串)中。
s1 = s1+s2;
String 类的 substring 方法用于此方法有两种变体,并返回一个新字符串,该字符串是此字符串的子字符串。子字符串从指定索引处的字符开始,延伸到 此字符串的末尾或直到 endIndex – 1,如果给出了第二个参数。
现在使用 String 类的 substring() 方法将 s1 的值存储在 s2 中,反之亦然。
s2 = s1.substring(0,i); s1 = s1.substring(i);
示例
public class Sample {
public static void main(String args[]){
String s1 = "tutorials";
String s2 = "point";
System.out.println("Value of s1 before swapping :"+s1);
System.out.println("Value of s2 before swapping :"+s2);
int i = s1.length();
s1 = s1+s2;
s2 = s1.substring(0,i);
s1 = s1.substring(i);
System.out.println("Value of s1 after swapping :"+s1);
System.out.println("Value of s2 after swapping :"+s2);
}
}
输出
Value of s1 before swapping :tutorials Value of s2 before swapping :point Value of s1 after swapping :point Value of s2 after swapping :tutorials

