Java中字符串反转的方法有以下几种:
String str = "Hello World";
StringBuilder sb = new StringBuilder(str);
sb.reverse();
String reversedStr = sb.toString();
System.out.println(reversedStr);
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
String str = "Hello World";
String reversedStr = reverseString(str);
System.out.println(reversedStr);
public static String reverseString(String str) {
char[] charArray = str.toCharArray();
int left = 0;
int right = charArray.length - 1;
while (left < right) {
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++;
right--;
}
return new String(charArray);
}
String str = "Hello World";
String reversedStr = reverseString(str);
System.out.println(reversedStr);
以上是常用的几种方法,根据需求选择适合的方法进行字符串反转。