Swapping a string is one of the most frequently asked question in
College exams. This is somewhat similar to Swapping two
Numbers.
Let us look at the logic behind swapping the strings Firstly, we need to declare two Strings whom we want to swap.
Like here we have declared s1 & s2. Then we have to concate them, and we will store them in variable s1. So s1 will now become: HelloJava.
Now in next step we will perform the operation on s1 i.e now HelloJava. So, s1.length(); will give length of string s1 and s2.length(); will give length of string s2. Then by using s1.substring(); we will get the length of string s1 from 0,5(Remember 5 will be exclusive here).
So, we will get only Hello and this will be stored in variable s2. Now, we need to remember that s2 is storing now Hello. So s2=Hello.
Let us look at the logic behind swapping the strings Firstly, we need to declare two Strings whom we want to swap.
Like here we have declared s1 & s2. Then we have to concate them, and we will store them in variable s1. So s1 will now become: HelloJava.
Now in next step we will perform the operation on s1 i.e now HelloJava. So, s1.length(); will give length of string s1 and s2.length(); will give length of string s2. Then by using s1.substring(); we will get the length of string s1 from 0,5(Remember 5 will be exclusive here).
So, we will get only Hello and this will be stored in variable s2. Now, we need to remember that s2 is storing now Hello. So s2=Hello.
s2.length(); in next step will give the length of Java that will be
equal to 5 because Hello is of length 5. Then s1.substring(5); will
continue from index 5 till end of string so Java will be stored in
s1.
Look into the code for clear implementation.
public class SwapString
{
public static void main(String args[])
{
String s1 = "Hello"; //here string length =8
String s2 = "Java"; //here string length =3;
s1 = s1+s2;
s2 = s1.substring(0,s1.length()-s2.length());
s1 = s1.substring(s2.length());
System.out.println(s1);
System.out.println(s2);
}
}
Output:
Java
Hello
Tags:
basic