String reverse with recursion

Steps:

  1. Create a method which receives String as argument and return String.
  2. Check is string is null or string length is less or equal to 1 then return the current string only.
  3. If string length is more then 1 then again call string reverse method with substring(1) and append it with charAt(0). So first character of each call will be appended from right to left.

Example: “abc” is string then

substring of 1 is bc + ‘a’.

substring of 1 is c+’b’+’a’

Example:

package com.gudla.randomprograms;

/**
 * Created by santhosh on 28/3/17.
 */
public class StringReverse {

    public static void main(String[] args) {
        System.out.println(reverse("android"));

    }

    private static String reverse(String s){
        if(s == null || s.length() <= 1 ) {
            return s;
        } else {
            return reverse(s.substring(1))+s.charAt(0);
        }
    }
}

Output:

diordna

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s