How can I replace the letter 'a' from a string and replace it with two more a's recursively?

New user :
import java.util.Scanner;

public class AddAs
{
    public static void main(String[] args)
    {
        Scanner sc1 = new Scanner(System.in);

        System.out.println("Please enter a word:");

        sc1.close();

        String n = ("aaa");

        char s = 'a';

        System.out.println(s2);

        String pp = moreAs(s2, s, n)

        System.out.println(pp);
    }

    public static String moreAs(String p, char s, String n, String s2)
    {
        if (p.length() < 1)
        {
            return p;
        }

        for (int i = 0; i < p.length(); i++)
        {
            if (p.charAt(i) == s)
            {
                p = p.substring(0, 1) + n + p.substring(++i)

                System.out.println(p);

                return moreAs(p, s, n)
            }
        }
    }

    return s2;
}

I'm writing a java program for work, the program must replace any occurrence of the letter 'a' with two more a' For example if the user inputs "anagram" the output would be "aaanaaagraaam". This must be done recursively, any ideas? I think i'm on the right track I'm not to sure, ask any questions. I do know I've a string called n which contains 3 a's but I thought If i removed one I have to replaced it with three a's.

Arvind Kumar Avinash :

You can do it using OOTB (Out-Of-The-Box) String::replaceAll function or by using your custom recursive function as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        System.out.println("Original string: " + str);
        System.out.println("Updated string: " + str.replaceAll("a", "aaa"));

        // Using recursive function
        System.out.println("Updated string (using recursive function): " + moreAs(str, 0));
    }

    static String moreAs(String str, int n) {
        if (n == str.length()) {
            return str;
        }
        if (str.charAt(n) == 'a') {
            // Call the function recursively after replacing 'a' with 'aaa' in str 
            return moreAs(str.substring(0, n + 1) + "aa" + str.substring(n + 1), n + 3);
        } else {
            // Call the function recursively without changing str
            return moreAs(str, n + 1);
        }
    }
}

A sample run:

Enter a string: anagram
Original string: anagram
Updated string: aaanaaagraaam
Updated string (using recursive function): aaanaaagraaam

The logic in the custom recursive function is simple and straight forward. Feel free to comment in case of any doubt/issue.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360434&siteId=1