In this tutorial we will learn how to reverse a string in java . There are mainly 3 ways to reverse the string.
Method 1-
public class StringReverse {
public static void main(String[] args) {
String str = "www.mycareerrepublic.com";
System.out.println("Original String: " + str);
char[] char_array = str.toCharArray();
System.out.print("Reversed String: ");
for (int i = char_array.length - 1; i >= 0; i--)
System.out.print(char_array[i]);
}
}
Original String: www.mycareerrepublic.com
Reversed String: moc.cilbuperreeracym.www
Method 2-
public class StringReverse {
public static void main(String[] args) {
String str = "www.mycareerrepublic.com";
System.out.println("Original String: " + str);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(str);
System.out.print("Reversed String: " + stringBuffer.reverse());
}
}
Original String: www.mycareerrepublic.com
Reversed String: moc.cilbuperreeracym.www
Method 3-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StringReverse {
public static void main(String[] args) {
String str = "www.mycareerrepublic.com";
System.out.println("Original String: " + str);
char[] char_array = str.toCharArray();
ListstrList = new ArrayList ();
for (Character character : char_array) {
strList.add(character);
}
System.out.print("Reversed String: ");
Collections.reverse(strList);
for (Character character : strList) {
System.out.print(character);
}
}
}
Original String: www.mycareerrepublic.com
Reversed String: moc.cilbuperreeracym.www
0 comments:
Post a Comment