Java - Write code to return a new string in which one search string is replaced by another.

Requirements

Write code to return a new string in which one search string is replaced by another.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String src = "book2s.com";
        String search = "o";
        String replace = "O";
        System.out.println(replace(src, search, replace));
    }//  ww w .j a  va2 s  .co m

    /**
     * returns a new string in which one search string is replaced by another.
     */
    public static String replace(String src, String search, String replace) {
        if (src == null)
            return src;
        if (search == null || search.length() == 0)
            throw new IllegalArgumentException(
                    "Search string must not be empty");

        String result = src;
        int ind = 0;
        while ((ind = result.indexOf(search, ind)) >= 0) {
            result = result.substring(0, ind) + replace
                    + result.substring(ind + search.length());
            ind += replace.length();
        }

        return result;
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when the index is out of bounds.
     */
    public static String substring(String str, int beginIndex) {
        if (str == null)
            return null;
        if (beginIndex < 0)
            return str;
        if (beginIndex >= str.length())
            return "";

        return str.substring(beginIndex);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when one or both of the indexes is out of bounds.
     */
    public static String substring(String str, int beginIndex, int endIndex) {
        if (str == null)
            return null;
        if (beginIndex > endIndex)
            return "";
        if (beginIndex < 0)
            beginIndex = 0;
        if (endIndex > str.length())
            endIndex = str.length();

        return str.substring(beginIndex, endIndex);
    }
}

Related Exercise