Java - Write code to Replace last occurrence of given sub string

Requirements

Write code to Replace last occurrence of given sub string

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String s = "book2s.com";
        String search = "book2s.com";
        System.out.println(removeLast(s, search));
    }//from w w  w .j  av a 2 s  . c o m

    /**
     * Replace last occurrence of given sub string
     *
     * @param s
     * @param search
     * @return
     */
    public static String removeLast(String s, String search) {
        int pos = s.lastIndexOf(search);

        if (pos > -1) {
            return s.substring(0, pos)
                    + s.substring(pos + search.length(), s.length());
        }

        return s;
    }
}

Related Exercise