如何在没有第三个变量的情况下交换两个字符串变量。
若要在没有第三者的情况下交换两个字符串(假定为 s1 和 s2)的内容,首先将它们连接起来并存储在 s1 中。现在使用字符串类的 substring() 方法将 s1 的值存储在 s2 中,反之亦然。
举例说明
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP