Swap two strings with using substring( ) function in Java

In this Java tutorial, we are going to swap two strings using pre-defined substring() function in Java.

What is substring() in Java?

substring() method in Java operates in two ways:

  • substring( int startindex ) :- This function will return the substring of the calling string from the startindex till the last character.

     Syntax :- substring ( int startindex );

  • substring ( int startindex , int endindex ) :- This function will return the substring of the calling string from the startindex(including) till the endindex (excluding).

Syntax :- substring ( int startindex , int endindex );  



Algorithm

  1. Take two strings a and b.
  2. Append second string to the first string using a+b;
  3. Store first string in second string using substring(startindex , endindex) function.
  4. Now, store second string in  first string using substring(startindex) function.

Code Snippet to store the second string in the first string and first in second string

b=a.substring(0,a.length()-b.length());
  
   a=a.substring(b.length());

Java Code to swap two strings using substring()

import java.util.*;

class Codespeedy

{
    public static void main ( String[] args )
    
   {
        String a = "Happy";
        
        String b = "New Year";
        
         System.out.println("String before swap : a = "+a+" ; b = "+b);
        
         a=a+b;
         
         b=a.substring(0,a.length()-b.length());
        
         a=a.substring(b.length());
         
         System.out.println("String after swap : a = "+a+"  ; b = "+b);
    }
}


OUTPUT

String before swap : a = Happy ; b = New Year

String after swap : a = New Year ; b = Happy

Also, learn

 

In the problem, we append the second string “b” to string “a”. Then, we store first string “a” in second string “b” by calling function a.substring(startindex , endindex) where pass startindex=0 , and endindex= (length of whole string – length of second string ) and we store second string in first string using substring ( startindex ) function where we pass startindex = length of second string and it will go till the last character by default.

 

Leave a Reply

Your email address will not be published. Required fields are marked *