Use substring() method
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); } }
Output:
Reverse of the given string is : sediugavaj
The above is the detailed content of How to reverse string using substring() method in Java?. For more information, please follow other related articles on the PHP Chinese website!