Java String Replace replace(String origStr, char oldChar, String newStr)

Here you can find the source of replace(String origStr, char oldChar, String newStr)

Description

Replaces a character of a String with characters in the specified new substring.

License

Apache License

Parameter

Parameter Description
origStr string that contains the replaceable substring
oldChar character to search in the orig String
newStr substring of the new characters

Return

if the parameters are correct returns the new string; otherwise if origStr parameter is null returns null. If newstr parameter is null returns origStr parameter

Declaration

public static String replace(String origStr, char oldChar, String newStr) 

Method Source Code

//package com.java2s;
/**/*from w  ww . j  av  a  2 s .  c o m*/
 * Copyright (C) 2012 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * Replaces a character of a String with characters in the specified
     * new substring.
     *
     * @param origStr string that contains the replaceable substring
     * @param oldChar character to search in the orig String
     * @param newStr  substring of the new characters
     * @return if the parameters are correct returns the new string; otherwise
     *         if origStr parameter is null returns null. If newstr parameter is
     *         null returns origStr parameter
     * @deprecated replaced by replaceAll()
     */
    public static String replace(String origStr, char oldChar, String newStr) {
        return replaceAll(origStr, oldChar, newStr);
    }

    /**
     * Replaces the characters in a substring of a String with characters in
     * the specified new substring.
     *
     * @param origStr original string
     * @param oldStr  substring to search in the orig String
     * @param newStr  new substring
     * @return if the parameters are correct returns the new string; otherwise
     *         if orig parameter is null returns null. If str or newstr parameters are
     *         null returns orig parameter
     * @deprecated replaced by replaceAll()
     */
    public static String replace(String origStr, String oldStr, String newStr) {
        return replaceAll(origStr, oldStr, newStr);
    }

    /**
     * Replaces a character of a String with characters in the specified
     * new substring.
     *
     * @param origStr string that contains the replaceable substring
     * @param oldChar character to search in the orig String
     * @param newStr  substring of the new characters
     * @return if the parameters are correct returns the new string; otherwise
     *         if origStr parameter is null returns null. If newstr parameter is
     *         null returns origStr parameter
     */
    public static String replaceAll(String origStr, char oldChar, String newStr) {
        if (origStr == null) {
            return null;
        } else if (newStr == null) {
            return origStr;
        }

        StringBuffer buffer = new StringBuffer(origStr);
        int index = origStr.indexOf(oldChar);
        int replIndex;
        int insertPadding = 0;
        int padding = newStr.length() - 1;
        while (index > -1) {
            replIndex = index + insertPadding;
            buffer.replace(replIndex, (replIndex + 1), newStr);
            index++;
            index = origStr.indexOf(oldChar, index);
            insertPadding += padding;
        }
        return buffer.toString();
    }

    /**
     * Replaces the characters in a substring of a String with characters in
     * the specified new substring.
     *
     * @param origStr original string
     * @param oldStr  substring to search in the orig String
     * @param newStr  new substring
     * @return if the parameters are correct returns the new string; otherwise
     *         if orig parameter is null returns null. If str or newstr parameters are
     *         null returns orig parameter
     */
    public static String replaceAll(String origStr, String oldStr, String newStr) {

        if (origStr == null) {
            return null;
        } else if (oldStr == null || newStr == null) {
            return origStr;
        }

        StringBuffer buf = new StringBuffer(origStr);
        int inicio = origStr.indexOf(oldStr);

        if (inicio == -1) {
            return origStr;
        }

        while (inicio != -1) {
            buf.replace(inicio, inicio + oldStr.length(), newStr);
            inicio = buf.toString().indexOf(oldStr, inicio + newStr.length());
        }

        return buf.toString();
    }

    /**
     * Replaces the characters in all substrings of a String with a String.
     *
     * @param str original string
     * @param in  substrings to search in the orig String
     * @param out new String
     * @return if the parameters are correct returns the new string; otherwise
     *         if some of the parameters is null returns the original string
     */
    private static String replaceAll(String str, String[] in, String out) {
        if (str == null || in == null || out == null) {
            return str; // for the sake of robustness
        }

        StringBuffer buffer = new StringBuffer(str);

        int idx = 0;
        for (int i = 0; i < in.length; i++) {
            idx = 0;
            while ((idx = indexOf(in[i], idx, buffer)) != -1) {
                buffer.replace(idx, idx + in[i].length(), out);
            }
        }
        return buffer.toString();
    }

    /**
     * Replaces the characters in all substrings of a String with characters in
     * the specified array of substrings.
     *
     * @param str original string
     * @param in  substrings to search in the orig String
     * @param out array of new substrings
     * @return if the parameters are correct returns the new string; otherwise
     *         if some of the parameters is null returns the original string
     */
    public static String replaceAll(String str, String[] in, String[] out) {
        if (str == null || in == null || out == null || in.length != out.length) {
            return str; // for the sake of robustness
        }

        StringBuffer buffer = new StringBuffer(str);

        int idx = 0;
        for (int i = 0; i < in.length; i++) {
            idx = 0;
            while ((idx = indexOf(in[i], idx, buffer)) != -1) {
                buffer.replace(idx, idx + in[i].length(), out[i]);
            }
        }
        return buffer.toString();
    }

    /**
     * Returns a String who replace Strings include into <I>str</I>,
     * which are into delimiters and known in <I>in</I>,
     * to corresponding String from <I>out</I>.
     * If in and out aren't of the same size, the string is returned
     * unchanged.
     *
     * @param str        String to manipulate
     * @param in         Vector which contains strings to find
     * @param out        Vector which contains strings to replace
     * @param beginDelim String who delimiters the begin of the substrings
     *                   into <I>str</I>
     * @param endDelim   String who delimiters the end of the substrings
     *                   into <I>str</I>
     * @return the new string
     */
    public static String replaceAll(String str, Vector in, Vector out, String beginDelim, String endDelim) {
        return replaceAll(str, (String[]) in.toArray(), (String[]) out.toArray(), beginDelim, endDelim);
    }

    /**
     * Returns a String who replace Strings include into <I>str</I>,
     * which are into delimiters and known in <I>in</I>,
     * to corresponding String from <I>out</I>.
     * <br>
     * If in and out aren't of the same size, the string is returned
     * unchanged.
     * <br>
     * beginDelim and endDelim can't be the same. If they are, a
     * IllegalArgumentException is throw.
     *
     * @param str        String to manipulate
     * @param in         array of strings to find
     * @param out        array of strings to replace
     * @param beginDelim String who delimiters the begin of the substrings
     *                   into <I>str</I>
     * @param endDelim   String who delimiters the end of the substrings
     *                   into <I>str</I>
     * @return the new string
     * @throws IllegalArgumentException if beginDelim and endDelim are equal
     */
    public static String replaceAll(String str, String[] in, String[] out, String beginDelim, String endDelim) {

        if (in.length != out.length) {
            return str;
        }

        if (beginDelim.equals(endDelim)) {
            throw new IllegalArgumentException("beginDelim and endDelim are equals: " + beginDelim);
        }

        StringBuffer str_ret = new StringBuffer();
        String sFound;
        String sOut;
        String lastSegment;
        int lastIndex = 0;
        int indexBegin = str.indexOf(beginDelim);
        int indexEnd = -1;
        int indexIn = -1;
        int index = -1;
        boolean found = false;
        int countIn = in.length;

        while (indexBegin > -1) {
            indexEnd = str.indexOf(endDelim, indexBegin);
            if (beginDelim.equals(endDelim) && beginDelim.equals("")) {
                indexEnd++;
            } else {
                index = str.indexOf(beginDelim, indexBegin + beginDelim.length());
                while (index > -1 && index < indexEnd) {
                    indexBegin = index;
                    index = str.indexOf(beginDelim, indexBegin + beginDelim.length());
                }
            }
            sFound = str.substring(indexBegin + beginDelim.length(), indexEnd);
            lastSegment = str.substring(lastIndex, indexBegin);
            sOut = "";
            found = false;
            indexIn = 0;
            while (!found && indexIn < countIn) {
                if (sFound.compareToIgnoreCase(in[indexIn]) == 0) {
                    sOut = indentParagraph(lastSegment, out[indexIn]);
                    found = true;
                }
                indexIn++;
            }
            //dejamos el tag para que se note el error de tag no existente
            if (!found) {
                sOut = beginDelim + sFound + endDelim;
            }
            //if no word to replace and after tag to replace you have a CR ignore
            if (found && sOut.compareTo("") == 0) {
                index = lastSegment.lastIndexOf('\n');
                if (index > -1 && lastSegment.substring(index + 1).trim().compareTo("") == 0) {
                    lastSegment = lastSegment.substring(0, index);
                }
            }

            str_ret.append(lastSegment).append(sOut);
            lastIndex = indexEnd + endDelim.length();
            indexBegin = str.indexOf(beginDelim, lastIndex);
        }
        if (lastIndex < str.length()) {
            str_ret.append(str.substring(lastIndex, str.length()));
        }

        return str_ret.toString();
    }

    /**
     * Returns the position of the first ocurrence of the substring into
     * the stringbuffer, or -1 if does not ocurr.
     * <br>
     * Returns the smaller i such that
     * <p/>
     * buf.substring(i, str.length()).equals(str),
     * <p/>
     * holds, and -1 if no such i exists.
     * <br>
     * Assumes str and buf are non-null.
     *
     * @param str substring to find
     * @param buf buffer to search into
     * @return the position of subStr into buf, or -1 if it does not ocurr
     */
    public static int indexOf(String str, StringBuffer buf) {
        return indexOf(str, 0, buf);
    }

    /**
     * Returns the position of the first ocurrence of the substring into
     * the stringbuffer, starting at fromIndex, or -1 if does not ocurr.
     * <br>
     * Returns the smaller i greater than or equals to fromIndex such that
     * <p/>
     * buf.substring(i, str.length()).equals(str),
     * <p/>
     * holds, and -1 if no such i exists.
     * <p/>
     * Assumes str and buf are non-null.
     *
     * @param str       substring to find
     * @param fromIndex the index to start the search from
     * @param buf       buffer to search into
     * @return the position of subStr into buf, or -1 if it does not ocurr
     */
    public static int indexOf(String str, int fromIndex, StringBuffer buf) {

        fromIndex = Math.max(fromIndex, 0);

        // begin degenerate cases
        if (fromIndex >= buf.length()) {
            if (fromIndex == 0 && str.length() == 0) {
                return 0;
            }
            return -1;
        }
        if (str.length() == 0) {
            return fromIndex;
        }
        // end degenerate cases

        int max = buf.length() - str.length();
        int i = fromIndex;
        while (true) {
            // look for the next occurrence of str.charAt(0)
            while (i <= max && buf.charAt(i) != str.charAt(0)) {
                ++i;
            }
            if (i > max) {
                return -1;
            }
            // once anchored, check the rest
            int j = i + 1, k = 1;
            while (k < str.length() && buf.charAt(j) == str.charAt(k)) {
                ++j;
                ++k;
            }
            if (k == str.length()) {
                return i; // all of them matched
            }
            ++i; // failed, try again
        }
    }

    /**
     * @see #substring(String,int,int)
     * @deprecated Use substring instead
     */
    public static String subString(String str, int beginIndex, int endIndex) {
        return substring(str, beginIndex, endIndex);
    }

    public static String substring(String str, int beginIndex, int endIndex) {
        if (str.length() < endIndex) {
            endIndex = str.length();
        }

        return str.substring(beginIndex, endIndex);
    }

    /**
     * Return a paragraph who insert spaces at the beginning of lines.
     * The amount of spaces that will be inserted is equals to the length of
     * all lines, ended with '\n', in the <i>textBefore</i> string, i.e, if
     * textBefore="in\nden\nstr" seven spaces will be inserted to indent the lines
     * of <i>textToModify</i> string.
     *
     * @param textBefore   String where extract the spaces to insert
     * @param textToModify String to modify
     * @return indented string
     * @deprecated Use indentParagraph(String,int) instead
     */
    public static String indentParagraph(String textBefore, String textToModify) {
        int indexU = textBefore.lastIndexOf('\n');
        return indentParagraph(textToModify, indexU + 1);
    }

    /**
     * Insert "indentSize" spaces before every line of textToModify.
     * If indentSize is negative or 0, the string is return unchanged
     *
     * @param textToModify string to indent
     * @param indentSize   number of spaces to insert
     * @return a string whith the lines indented
     */
    public static String indentParagraph(String textToModify, int indentSize) {
        int indexU;
        StringBuffer text;
        String textBegin;
        String textRest;
        String blanks;

        if (indentSize > 0) {
            blanks = repeat(" ", indentSize);
            indexU = textToModify.indexOf('\n');
            if (indexU > -1) {
                textRest = textToModify;
                text = new StringBuffer();
                while (indexU > -1) {
                    textBegin = textRest.substring(0, indexU + 1);
                    textRest = textRest.substring(indexU + 1).trim();
                    text.append(blanks).append(textBegin);
                    indexU = textRest.indexOf('\n');
                }
                text.append(blanks).append(textRest);

                return text.toString();
            } else {
                return textToModify;
            }
        } else {
            return textToModify;
        }
    }

    /**
     * Repeat a String n times.
     *
     * @param str String to repeat
     * @param num number times to repeat
     * @return a String who repeats <I>str</I>, <I>num</I> times.
     */
    public static String repeat(String str, int num) {
        StringBuffer str_ret = new StringBuffer(str.length() * num);

        for (int i = 0; i < num; i++) {
            str_ret.append(str);
        }

        return str_ret.toString();
    }
}

Related

  1. getLineBreakOffsets(String replacementString)
  2. replace(final String text, final String search, final String replace)
  3. replace(String source, Properties properties)
  4. replace(String source, String oldChars, String newChars)
  5. replace(String source, String stringToReplace, String replacementString, boolean matchCase)
  6. replace(String str)