Java Map Substitute substitute(String s, Map map)

Here you can find the source of substitute(String s, Map map)

Description

Substitutes alls occurences of several patterns in a string.

License

Apache License

Parameter

Parameter Description
s String to work on
map Map containing the patterns as keys and the replacements as values

Return

The result string or s itself if the string does not contain any of the patterns

Declaration

public static String substitute(String s, Map map) 

Method Source Code

//package com.java2s;
/*/* ww  w .  j  a  v  a2s  .  c o  m*/
 *   Copyright 2007 skynamics AG
 *
 *   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.Iterator;

import java.util.Map;
import java.util.Set;

public class Main {
    /**
     * Substitutes alls occurences of a pattern in a string.
     *
     * @param s String to work on or null
     * @param pattern Pattern to search for
     * @param replacement String to replace for the pattern or null for nothing
     * @return The result string or s itself if the pattern was not found
     */
    public static String substitute(String s, String pattern, String replacement) {
        if (s == null || pattern == null)
            return s;
        if (s.indexOf(pattern) < 0) {
            // Prevents unnecessary allocation and parsing
            // in case the string does not contain the pattern
            return s;
        }

        int patLen = pattern.length();
        if (patLen == 0)
            return s;

        int len = s.length();
        StringBuffer sb = new StringBuffer(len > 16 ? len : 16);

        for (int i = 0; i < len; ++i) {
            if (s.startsWith(pattern, i)) {
                if (replacement != null) {
                    sb.append(replacement);
                }
                i += patLen - 1;
            } else {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }

    /**
     * Substitutes alls occurences of several patterns in a string.
     * The pattern comparisons case-dependent.
     *
     * @param s String to work on
     * @param map Map containing the patterns as keys and the replacements as values
     * @return The result string or s itself if the string does not contain any of the patterns
     */
    public static String substitute(String s, Map map) {
        return substitute(s, map, false);
    }

    /**
     * Substitutes alls occurences of several patterns in a string.
     *
     * @param s String to work on
     * @param map Map containing the patterns as keys and the replacements as values
     * @param ignoreCase
     *      true   Ignores character casing when comparing the string to the patterns<br>
     *      false   Comparisons are case-dependent
     * @return The result string or s itself if the string does not contain any of the patterns
     */
    private static String substitute(String s, Map map, boolean ignoreCase) {
        if (s == null || map == null)
            return s;

        // We need to iterate the
        Set patternSet = map.keySet();
        if (patternSet.size() == 0)
            return s;

        // We are allocating the string buffer only if we really need it,
        // i. e. if there is something to replace
        StringBuffer sb = null;

        int len = s.length();
        for (int i = 0; i < len; ++i) {
            String matchingPattern = null;

            for (Iterator it = patternSet.iterator(); it.hasNext();) {
                String pattern = (String) it.next();

                boolean match = ignoreCase ? s.regionMatches(true, i, pattern, 0, pattern.length())
                        : s.startsWith(pattern, i);

                if (match) {
                    matchingPattern = pattern;
                    break;
                }
            }
            if (matchingPattern != null) {
                if (sb == null) {
                    // First replace action, copy the string so far
                    sb = new StringBuffer(len > 16 ? len : 16);
                    sb.append(s.substring(0, i));
                }
                sb.append((String) map.get(matchingPattern));
                i += matchingPattern.length() - 1;
            } else {
                if (sb != null)
                    sb.append(s.charAt(i));
            }
        }

        return sb != null ? sb.toString() : s;
    }

    /**
     * Appends 2 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2) {
        sb.append(s1);
        sb.append(s2);
    }

    /**
     * Appends 3 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2, String s3) {
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
    }

    /**
     * Appends 4 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2, String s3, String s4) {
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
        sb.append(s4);
    }

    /**
     * Appends 5 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2, String s3, String s4, String s5) {
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
        sb.append(s4);
        sb.append(s5);
    }
}

Related

  1. subsituteAttr(Map attrMap, String text)
  2. substitute(String aString, Map variablesValues, String open, String close)
  3. substitute(String page, String payRef, String name, String emailAddress, String when, String license, Map map)
  4. substitute(String s, Map map)
  5. substitute(String str, Map subs)
  6. substitute(String str, Map subs)
  7. substituteExpressionLanguage(String stringToParse, Map variableMap)