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);
以上是常用的幾種方法,根據需求選擇適合的方法進行字符串反轉。