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
- Take two strings a and b.
- Append second string to the first string using a+b;
- Store first string in second string using substring(startindex , endindex) function.
- Now, store second string in first string using substring(startindex) function.
- How to remove null values from a String array in Java in various ways
- Segregating ‘R’ ‘G’ ‘B’ in a string in Java
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
- String Transformation in Java using Dynamic Programming
- How to remove non-alphabetical characters from a string in JAVA
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