Java Map Replace replaceFromMap(final String string, final Map replacements)

Here you can find the source of replaceFromMap(final String string, final Map replacements)

Description

replace From Map

License

Open Source License

Declaration

public static String replaceFromMap(final String string, final Map<String, String> replacements) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {
    public static String replaceFromMap(final String string, final Map<String, String> replacements) {
        StringBuilder sb = new StringBuilder(string);
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            final int start = sb.indexOf(key, 0);
            replaceString(sb, key, value, start);
        }/*  w  w w. j av  a 2  s .  com*/
        return sb.toString();
    }

    private static void replaceString(final StringBuilder sb, final String key, final String value, int start) {
        while (start > -1) {
            final int end = start + key.length();
            final int nextSearchStart = start + value.length();
            sb.replace(start, end, value);
            start = sb.indexOf(key, nextSearchStart);
        }
    }

    public static String replace(final String string, final String target, final String replacement) {
        final StringBuilder sb = new StringBuilder(string);
        final int start = sb.indexOf(target, 0);
        replaceString(sb, target, replacement, start);
        return sb.toString();
    }
}

Related

  1. replaceByMap(String tpl, Map map)
  2. replaceCharacters(String sequence, Map map, boolean reverse)
  3. replaceCharactersInArray(char[] characters, Map replacements)
  4. replaceElements(Map destinationMap, Map sourceMap)
  5. replaceEntities(final Map replacements, final String xml)
  6. replaceFromMap(String string, Map replacements)
  7. replaceGlobalTokensFromMap(Map dataMap, String message)
  8. replaceInvalid(String uri, Map reps)
  9. replaceKey(final Map map, final TKey oldkey, final TKey newkey)