Java不使用临时变量交换两个字符串变量
算法
步骤1: START
步骤2: 定义字符串str1 ="Good",str2 ="morning"进行交换
步骤3: 打印"交换前的字符串" str1,str2
步骤4: str1 = str1 + str2
步骤5: 使用子字符串函数从索引0到长度(str1)-(str2)提取str1并将其存储在str2中。
步骤6: 使用子字符串函数从索引长度(str2)提取str1到结束,并将其存储在str1中。
步骤7: 打印"交换后的字符串" str1,str2。
步骤8: END
程序:
public class SwapStrings
{
public static void main(String[] args) {
String str1 = "Good ", str2 = "morning ";
System.out.println("Strings before swapping: " + str1 + " " + str2);
//Concatenate both the string str1 and str2 and store it in str1
str1 = str1 + str2;
//Extract str2 from updated str1
str2 = str1.substring(0, (str1.length() - str2.length()));
//Extract str1 from updated str1
str1 = str1.substring(str2.length());
System.out.println("Strings after swapping: " + str1 + " " + str2);
}
}
输出:
Strings before swapping: Good morning
Strings after swapping: morning Good