Home > Java > javaTutorial > body text

How to reverse characters using recursion in java

PHPz
Release: 2023-04-27 11:04:15
forward
1548 people have browsed it

Use recursion

package net.javaguides.corejava.string;
/**
* 
* @author yisu
*
*/
public class UsingRecursion {
static int i = 0;
// Recursive function to reverse a string in Java using static variable
private static void reverse(char[] str, int k) {
// if we have reached the end of the string
if (k == str.length)
return;
// recurse for next character
reverse(str, k + 1);
if (i <= k) {
char temp = str[k];
str[k] = str[i];
str[i++] = temp;
}
}
public static String reverse(String str) {
// base case: if string is null or empty
if (str == null || str.equals(""))
return str;
// convert string into a character array
char[] A = str.toCharArray();
// reverse character array
reverse(A, 0);
// convert character array into the string
return String.copyValueOf(A);
}
public static void main(String[] args) {
String str = "Java Guides";
// 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 : sediuG avaJ
Copy after login

The above is the detailed content of How to reverse characters using recursion 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