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

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

王林
Release: 2023-04-21 23:28:06
forward
1202 people have browsed it

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);
}
}
Copy after login

Output:

Reverse of the given string is : sediugavaj
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template