📌  相关文章
📜  Java程序在不使用任何第三个变量的情况下交换两个字符串

📅  最后修改于: 2022-05-13 01:54:58.693000             🧑  作者: Mango

Java程序在不使用任何第三个变量的情况下交换两个字符串

给定两个字符串变量 a 和 b,您的任务是编写一个Java程序来交换这些变量,而不使用任何临时变量或第三个变量。允许使用库方法。

例子:

Input: a = "Hello"
       b = "World"

Output:
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello

方法:为了在不使用任何临时变量或第三个变量的情况下交换两个字符串变量,想法是使用字符串连接和 substring() 方法来执行此操作。 substring() 方法有两种形式,如下所示:

  • substring(int beginindex):此函数将返回调用字符串的子字符串,从作为参数传递给此函数的索引开始,直到调用字符串中的最后一个字符。
  • substring(int beginindex, int endindex):此函数将返回调用字符串的子字符串,该字符串从 beginindex(inclusive) 开始,到 endindex(exclusive) 作为参数传递给此函数。

算法:

1) Append second string to first string and 
   store in first string:
   a = a + b

2) call the method substring(int beginindex, int endindex)
   by passing beginindex as 0 and endindex as,
      a.length() - b.length():
   b = substring(0,a.length()-b.length());

3) call the method substring(int beginindex) by passing 
   b.length() as argument to store the value of initial 
   b string in a
   a = substring(b.length());

代码:

Java
// Java program to swap two strings without using a temporary
// variable.
import java.util.*;
  
class Swap
{    
    public static void main(String args[])
    {
        // Declare two strings
        String a = "Hello";
        String b = "World";
          
        // Print String before swapping
        System.out.println("Strings before swap: a = " + 
                                       a + " and b = "+b);
          
        // append 2nd string to 1st
        a = a + b;
          
        // store initial string a in string b
        b = a.substring(0,a.length()-b.length());
          
        // store initial string b in string a
        a = a.substring(b.length());
          
        // print String after swapping
        System.out.println("Strings after swap: a = " + 
                                     a + " and b = " + b);        
    }    
}


输出
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello