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

Requirements

Write code to replaces '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 = "o";
        String newSub = "O";
        System.out.println(replaceFirstSubstring(orig, origSub, newSub));
    }/*from w  w w .j a v a  2 s  . c om*/

    /**
     * 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