Java - Write code to replace All Substrings recursively

Requirements

Write code to replace All Substrings recursively

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        StringBuffer orig = new StringBuffer();
        String origSub = "book2s.com";
        String newSub = "book2s.com";
        System.out.println(replaceAllSubstrings(orig, origSub, newSub));
    }//from w  w  w  . j av a2s. co  m

    static public StringBuffer replaceAllSubstrings(StringBuffer orig,
            String origSub, String newSub) {
        StringBuffer result = new StringBuffer();
        result.append(replaceAllSubstrings(orig.toString(), origSub, newSub));
        return result;
    }

    static public String replaceAllSubstrings(String orig, String origSub,
            String newSub) {
        int first = orig.indexOf(origSub);
        if (first == -1) {
            return orig;
        }
        int last = first + origSub.length();
        String result = orig.substring(0, first);
        String rest = orig.substring(last);
        result = result + newSub
                + replaceAllSubstrings(rest, origSub, newSub);
        return result;
    }
}

Related Exercise