In Java, you can reverse a string using several different methods. Here are three common approaches:
Tweet
- Using a StringBuilder or StringBuffer class:
String original = "hello world";
StringBuffer reversed = new StringBuffer(original);
reversed = reversed.reverse();
System.out.println(reversed);
This approach creates a
TweetStringBuffer
object from the original string, then calls thereverse()
method to reverse the order of its characters. ThetoString()
method can then be used to get the reversed string as aString
object.
- Using a char array:
String original = "hello world";
char[] chars = original.toCharArray();
int length = chars.length;
for (int i = 0; i < length / 2; i++) {
char temp = chars[i];
chars[i] = chars[length - 1 - i];
chars[length - 1 - i] = temp;
}
String reversed = new String(chars);
System.out.println(reversed);
This approach converts the original string to a
Tweetchar
array, then swaps the characters from the beginning of the array with the characters from the end of the array until the middle of the array is reached. Finally, thechar
array is converted back to aString
object.
- Using recursion:
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
String original = "hello world";
String reversed = reverseString(original);
System.out.println(reversed);
This approach uses recursion to reverse the string. The
TweetreverseString()
method takes the original string and recursively calls itself with a substring of the original string that excludes the first character. Once the base case is reached (when the string is empty), the method re
All three of these methods will produce the same output: dlrow olleh
. You can choose the one that works best for your specific use case.