反转字符串

123 阅读1分钟
  1. 使用StringBuilder或StringBuffer:

    • StringBuilderStringBuffer 类都有 reverse 方法,可以方便地反转字符串。
    public class ReverseString {
        public static void main(String[] args) {
            String original = "Hello, World!";
            
            // 使用StringBuilder
            StringBuilder reversedBuilder = new StringBuilder(original).reverse();
            String reversedStringBuilder = reversedBuilder.toString();
            System.out.println("Reversed with StringBuilder: " + reversedStringBuilder);
    
            // 使用StringBuffer
            StringBuffer reversedBuffer = new StringBuffer(original).reverse();
            String reversedStringBuffer = reversedBuffer.toString();
            System.out.println("Reversed with StringBuffer: " + reversedStringBuffer);
        }
    }
    
  2. 使用toCharArray和数组操作:

    • 将字符串转换为字符数组,然后使用数组操作进行反转。
    public class ReverseString {
        public static void main(String[] args) {
            String original = "Hello, World!";
            
            // 使用toCharArray和数组操作
            char[] charArray = original.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--;
            }
    
            String reversedCharArray = new String(charArray);
            System.out.println("Reversed with charArray: " + reversedCharArray);
        }
    }
    
  3. 使用递归:

    • 通过递归来反转字符串。
    public class ReverseString {
        public static void main(String[] args) {
            String original = "Hello, World!";
            
            // 使用递归
            String reversedRecursive = reverseRecursive(original);
            System.out.println("Reversed with recursion: " + reversedRecursive);
        }
    
        private static String reverseRecursive(String str) {
            if (str.isEmpty()) {
                return str;
            } else {
                return reverseRecursive(str.substring(1)) + str.charAt(0);
            }
        }
    }