如何在沒有第三個變數的情況下交換兩個字串變數。
若要在沒有第三者的情況下交換兩個字串(假定為 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