Java - Write code to Search and replaces fixed string matches within the given string.

Requirements

Write code to Search and replaces fixed string matches within the given string.

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *//*from  w  w w . java2s .c  o  m*/
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String original = "book2s.com";
        String replaceFrom = "o";
        String replaceTo = "O";
        System.out.println(replace(original, replaceFrom, replaceTo));
    }

    private static final String EMPTY_STRING = "" /* NOI18N */.intern();

    /**
     * Search and replaces fixed string matches within the given string.
     *
     * @param original the original string.
     * @param replaceFrom the substring to be find.
     * @param replaceTo the substring to replace it with.
     *
     * @return new string with all occurrences replaced.
     */
    public static String replace(String original, String replaceFrom,
            String replaceTo) {
        if (EMPTY_STRING.equals(replaceFrom)) {
            return original;
        }

        if (original.indexOf(replaceFrom) == -1) {
            return original;
        }

        StringBuffer buf = new StringBuffer(original.length());
        int index = 0;

        for (;;) {
            int pos = original.indexOf(replaceFrom, index);

            if (pos == -1) {
                buf.append(original.substring(index));

                return buf.toString();
            }

            buf.append(original.substring(index, pos));
            buf.append(replaceTo);
            index = pos + replaceFrom.length();

            if (index == original.length()) {
                return buf.toString();
            }
        }
    }

    /**
     * Returns the index within the given string of the <em>x.</em> occurrence of the
     * specified character.
     *
     * @param character character to search.
     * @param str the string to search.
     * @param x <em>x.</em> occurrence of the character to search for.
     *
     * @return s the index within the given string of the <em>x.</em> occurrence of the
     *         given character. Returns <code>-1</code> if the specified character is
     *         not contained in the given string or it occurs less than the specified
     *         occurrence to look for.
     */
    public static int indexOf(char character, String str, int x) {
        for (int i = 1, pos = -1; (pos = str.indexOf(character, pos + 1)) > -1; i++) {
            if (i == x) {
                return pos;
            }
        }

        return -1;
    }
}

Related Exercise