|
String Reverse
Print the reverse of a given string.
|
package com.bethecoder.tutorials.coding.examples;
public class StringReverseTest {
/**
* @param args
*/
public static void main(String[] args) {
String str = "ABCD";
System.out.println("Reverse of '" + str + "' : " + reverse(str));
str = "JAVA";
System.out.println("Reverse of '" + str + "' : " + reverse(str));
str = "ABCD";
System.out.println("Reverse of '" + str + "' : " + reverse2(str));
str = "JAVA";
System.out.println("Reverse of '" + str + "' : " + reverse2(str));
}
private static String reverse(String str) {
return new StringBuffer(str).reverse().toString();
}
private static String reverse2(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < str.length() ; i ++) {
sb.append(str.charAt(str.length() - 1 - i));
}
return sb.toString();
}
}
|
| |
It gives the following output,
Reverse of 'ABCD' : DCBA
Reverse of 'JAVA' : AVAJ
Reverse of 'ABCD' : DCBA
Reverse of 'JAVA' : AVAJ
|
|