使用 substring() 方法
package net.javaguides.corejava.string; /** * * @author Ramesh Fadatare * */ public class UsingSubStringFunction { // Function to reverse a string in Java using recursion private static String reverse(String str) { // base case: if string is null or empty if (str == null || str.equals("")) return str; // last character + recurse for remaining string return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1)); } public static void main(String[] args) { String str = "javaguides"; // string is immutable str = reverse(str); System.out.println("Reverse of the given string is : " + str); } }
输出:
Reverse of the given string is : sediugavaj
以上是如何使用Java中的substring()方法进行字符串反转?的详细内容。更多信息请关注PHP中文网其他相关文章!