欢迎访问宙启技术站
智能推送

Java函数实例:如何实现字符串倒序输出

发布时间:2023-06-29 18:18:44

实现字符串倒序输出可以使用以下几种方法:

方法一:使用 StringBuilder 类的 reverse 方法

public class Main {
    public static void main(String[] args) {
        String str = "Hello, world!";
        
        StringBuilder sb = new StringBuilder(str);
        sb.reverse();
        String reverseStr = sb.toString();
        
        System.out.println(reverseStr);
    }
}

方法二:使用递归的方式实现字符串倒序输出

public class Main {
    public static void main(String[] args) {
        String str = "Hello, world!";
        
        String reverseStr = reverseString(str);
        
        System.out.println(reverseStr);
    }
    
    public static String reverseString(String str) {
        if (str.isEmpty()) {
            return str;
        }
        
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

方法三:使用字符数组实现字符串倒序输出

public class Main {
    public static void main(String[] args) {
        String str = "Hello, world!";
        
        char[] charArray = str.toCharArray();
        
        for (int i = charArray.length - 1; i >= 0; i--) {
            System.out.print(charArray[i]);
        }
    }
}

这些方法都能够实现字符串倒序输出,具体选择哪种方法取决于个人的偏好和具体的应用场景。