Program to Reverse a String
Input:
str="Navnath"
Original String is: "Navnath"
Output:
revstr="htanvaN"
Reverse String is: "htanvaN"
Solution:
Language Used: Java
Approach 1:
String Concatination
import java.util.Scanner;
public class reverse_string {
public static void main(String[] args) {
Scanner s= new Scanner(System.in) ;
System.out.println("Enter the string");
String str = s.next() ;
String revstr = " " ;
int len=str.length() ;
System.out.println("Original String is: "+ str);
for(int i=len-1;i>=0;i--)
{
revstr = revstr+str.charAt(i) ;
}
System.out.println("Reverse String is: "+ revstr);
}
}
Approach 2:
By Using StringBuffered Class
import java.util.Scanner;
public class reverse_string {
public static void main(String[] args) {
Scanner s= new Scanner(System.in) ;
System.out.println("Enter the string");
String str = s.next() ;
System.out.println("Original String is: "+ str);
StringBuffer sb = new StringBuffer(str) ;
StringBuffer revstr = sb.reverse() ;
System.out.println("Reverse String is: "+ revstr);
}
}
Approach 3:
By using StringBuilder Class
import java.util.Scanner;
public class reverse_string {
public static void main(String[] args) {
Scanner s= new Scanner(System.in) ;
System.out.println("Enter the string");
String str = s.next() ;
System.out.println("Original String is: "+ str);
StringBuilder sbl = new StringBuilder() ;
sbl.append(str) ;
StringBuilder revstr = sbl.reverse() ;
System.out.println("Reverse String is: "+ revstr);
}
}