如何在沒有第三個變數的情況下交換兩個字串變數。
若要交換兩個字串(假設為 s1 和 s2)的內容,而沒有第三個變數,首先將它們連線起來並存儲在 s1 中。現在使用 String 類 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP