Home  >  Article  >  Java  >  How to reverse string using substring() method in Java?

How to reverse string using substring() method in Java?

王林
王林forward
2023-04-21 23:28:061062browse

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete