Java String Replace replace(final String text, final String search, final String replace)

Here you can find the source of replace(final String text, final String search, final String replace)

Description

Replaces all occurrences of search in text by replace and returns the result.

License

Open Source License

Parameter

Parameter Description
text text to work on, can be <code>null</code>
search replace this text by <code>replace</code>, can be <code>null</code>
replace replacement for <code>search</code>, can be <code>null</code>

Return

resulting string (is never null)

Declaration

public static String replace(final String text, final String search, final String replace) 

Method Source Code

//package com.java2s;
/* This file is part of the project "Hilbert II" - http://www.qedeq.org
 *
 * Copyright 2000-2013,  Michael Meyling <mime@qedeq.org>.
 *
 * "Hilbert II" is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *///from   ww w .  j  a v a2 s  . c o  m

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

public class Main {
    /**
     * Replaces all occurrences of <code>search</code> in <code>text</code>
     * by <code>replace</code> and returns the result.
     *
     * @param   text    text to work on, can be <code>null</code>
     * @param   search  replace this text by <code>replace</code>, can be <code>null</code>
     * @param   replace replacement for <code>search</code>, can be <code>null</code>
     * @return  resulting string (is never <code>null</code>)
     */
    public static String replace(final String text, final String search, final String replace) {

        if (text == null) {
            return "";
        }
        final int len = search != null ? search.length() : 0;
        if (len == 0) {
            return text;
        }
        final StringBuffer result = new StringBuffer();
        int pos1 = 0;
        int pos2;
        while (0 <= (pos2 = text.indexOf(search, pos1))) {
            result.append(text.substring(pos1, pos2));
            if (replace != null) {
                result.append(replace);
            }
            pos1 = pos2 + len;
        }
        if (pos1 < text.length()) {
            result.append(text.substring(pos1));
        }
        return result.toString();
    }

    /**
     * Replaces all occurrences of <code>search</code> in <code>text</code>
     * by <code>replace</code>.
     *
     * @param   text    Text to work on. Must not be <code>null</code>.
     * @param   search  replace this text by <code>replace</code>. Can be <code>null</code>.
     * @param   replace replacement for <code>search</code>. Can be <code>null</code>.
     * @throws  NullPointerException    <code>text</code> is <code>null</code>.
     */
    public static void replace(final StringBuffer text, final String search, final String replace) {
        if (search == null || search.length() <= 0) {
            return;
        }
        final StringBuffer result = new StringBuffer(text.length() + 16);
        int pos1 = 0;
        int pos2;
        final int len = search.length();
        while (0 <= (pos2 = text.indexOf(search, pos1))) {
            result.append(text.substring(pos1, pos2));
            result.append(replace != null ? replace : "");
            pos1 = pos2 + len;
        }
        if (pos1 < text.length()) {
            result.append(text.substring(pos1));
        }
        text.setLength(0);
        text.append(result);
    }

    /**
     * Return substring of text. Position might be negative if length is big enough. If the string
     * limits are exceeded this method returns at least all characters within the boundaries.
     * If no characters are within the given limits an empty string is returned.
     *
     * @param   text        Text to work on. Must not be <code>null</code>.
     * @param   position    Starting position. Might be negative.
     * @param   length      Maximum length to get.
     * @return  Substring of maximum length <code>length</code> and starting with position.
     * @throws  NullPointerException    <code>text</code> is <code>null</code>.
     */
    public static String substring(final String text, final int position, final int length) {
        final int start = Math.max(0, position);
        int l = position + length - start;
        if (l <= 0) {
            return "";
        }
        int end = start + l;
        if (end < text.length()) {
            return text.substring(start, end);
        }
        return text.substring(start);
    }

    /**
     * Returns a readable presentation of an Object array. Something like ("a", null, 13)" if we have
     * the "a", null, 13. Objects of type {@link CharSequence} are quoted.
     *
     * @param   list  List of Objects.
     * @return  List notation.
     */
    public static String toString(final Object[] list) {
        final StringBuffer buffer = new StringBuffer(30);
        buffer.append("(");
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                if (i > 0) {
                    buffer.append(", ");
                }
                if (list[i] instanceof CharSequence) {
                    buffer.append("\"");
                    buffer.append(list[i].toString());
                    buffer.append("\"");
                } else {
                    buffer.append(String.valueOf(list[i]));
                }
            }
        }
        buffer.append(")");
        return buffer.toString();
    }

    /**
     * Returns a readable presentation of a Set. Something like {"a", null, "13} if we have
     * "a", null, 13. Objects of type {@link CharSequence} are quoted.
     *
     * @param   set Set of objects.
     * @return  Set notation for toString() results.
     */
    public static String toString(final Set set) {
        final StringBuffer buffer = new StringBuffer(30);
        buffer.append("{");
        if (set != null) {
            Iterator e = set.iterator();
            boolean notFirst = false;
            while (e.hasNext()) {
                if (notFirst) {
                    buffer.append(", ");
                } else {
                    notFirst = true;
                }
                final Object obj = e.next();
                if (obj instanceof CharSequence) {
                    buffer.append("\"");
                    buffer.append(String.valueOf(obj));
                    buffer.append("\"");
                } else {
                    buffer.append(String.valueOf(obj));
                }
            }
        }
        buffer.append("}");
        return buffer.toString();
    }

    /**
     * Returns a readable presentation of a Map. Something like "{a=2, b=null, c=12}" if the
     * Map contains (a, 2), (b, null), (c, 12).
     *
     * @param   map Map of objects mappings.
     * @return  Set notation for toString() results.
     */
    public static String toString(final Map map) {
        final StringBuffer buffer = new StringBuffer(30);
        buffer.append("{");
        if (map != null) {
            Iterator e = map.entrySet().iterator();
            boolean notFirst = false;
            while (e.hasNext()) {
                if (notFirst) {
                    buffer.append(", ");
                } else {
                    notFirst = true;
                }
                final Map.Entry entry = (Map.Entry) e.next();
                buffer.append(String.valueOf(entry.getKey()));
                buffer.append("=");
                final Object value = entry.getValue();
                if (value instanceof CharSequence) {
                    buffer.append("\"");
                    buffer.append(String.valueOf(value));
                    buffer.append("\"");
                } else {
                    buffer.append(String.valueOf(value));
                }
            }
        }
        buffer.append("}");
        return buffer.toString();
    }
}

Related

  1. getLineBreakOffsets(String replacementString)
  2. replace(String origStr, char oldChar, String newStr)
  3. replace(String source, Properties properties)
  4. replace(String source, String oldChars, String newChars)
  5. replace(String source, String stringToReplace, String replacementString, boolean matchCase)