Reverse String in java (Three ways to reverse string)
There are three ways
to reverse the string :
1) Using For Loop
2) Using Recursion
3) Using StringBuilder
Reverse string Using
For loop :
public class
ReverseString{
public static void
main(String[] args) {
String origional =
"Programming";
String reverse =
"";
for (int i =
origional.length() - 1; i >= 0; i--) {
reverse = reverse
+ origional.charAt(i);
}
System.out.println("Reverse
String is : " + reverse);
}
}
Output:
Reverse String is :
gnimmargorP
Reverse string using Recursion:
public class
recursion1 {
public static void
main(String[] args) {
recursion1 rsr =
new recursion1();
String Origional =
"Programming";
String reverse =
rsr.recursion(Origional);
System.out.println("Reverse
string is:" + reverse);
}
public String
recursion(String orig) {
if (orig.length()
== 1)
return orig;
else
return
orig.charAt(orig.length() - 1) + recursion(orig.substring(0,
orig.length() - 1));
}
}
Output:
Reverse String is :
gnimmargorP
Reverse string using String Builder:
public class
reversemethod {
public static void
main(String[] args) {
String Java =
"Programming";
StringBuilder sb =
new StringBuilder(Java);
System.out.println("Reverse
string is: " + sb.reverse());
}
}
Output:
Reverse String is :
gnimmargorP
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home