Java - Write code to replace Last Substring

Requirements

Write code to replace Last Substring

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(replaceLastSubstring(orig, origSub, newSub));
    }/*www .j  a v  a2 s  . c o  m*/

    public static String replaceLastSubstring(String orig, String origSub,
            String newSub) {
        int first = orig.lastIndexOf(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