Java - Write code to replace 'origSub' with 'newSub' in the String 'orig'.

Requirements

Write code to replace 'origSub' with 'newSub' in the String 'orig'.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String orig = "book2s.com";
        String origSub = "book2s.com";
        String newSub = "book2s.com";
        System.out.println(replaceFirstSubstring(orig, origSub, newSub));
    }/*  ww w.  java  2  s. c  o m*/

    /**
     * replaces 'origSub' with 'newSub' in the String 'orig'.
     * 
     * @param orig
     * @param origSub
     * @param newSub
     * @return String
     */
    static public String replaceFirstSubstring(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);
        result = result + newSub + orig.substring(last);
        return result;
    }
}

Related Exercise