Java Map Replace replaceTokens(String inputString, Map tokenMap)

Here you can find the source of replaceTokens(String inputString, Map tokenMap)

Description

Replace all tokens in a String.

License

Open Source License

Parameter

Parameter Description
inputString the String where the tokens shall be replaced
tokenMap the Map of tokens and their replacements

Return

the String with the token replaced

Declaration

public static String replaceTokens(String inputString, Map<String, String> tokenMap) 

Method Source Code

//package com.java2s;
// compliance with the InfoGrid license. The InfoGrid license and important

import java.util.Iterator;
import java.util.Map;

public class Main {
    /**//from w  w  w  . jav  a 2s. co  m
     * Replace all tokens in a String.
     *
     * @param inputString the String where the tokens shall be replaced
     * @param tokenMap the Map of tokens and their replacements
     * @return the String with the token replaced
     */
    public static String replaceTokens(String inputString, Map<String, String> tokenMap) {
        StringBuilder ret = new StringBuilder(inputString.length() + 10);
        Iterator<String> iter = tokenMap.keySet().iterator();

        ret.append(inputString);

        while (iter.hasNext()) {
            String token = iter.next();
            String value = tokenMap.get(token);

            int found = 0;
            while ((found = ret.indexOf(token, found)) > 0) {
                ret.replace(found, found + token.length(), value);
            }
        }
        return ret.toString();
    }
}

Related

  1. replaceSeparator(String value, String separator, Map map)
  2. replaceString(Map bodyToReplace, String replacingContent)
  3. replaceString(String source, Map args)
  4. replaceString(String uri, String baseURI, Map prefixes)
  5. replaceTemplates(String template, Map entries)
  6. replaceToStringBuilder(String s, String begin, String end, Map values)
  7. replaceValues(String s, String begin, String end, Map values)
  8. replaceValuesToSynonyms(Map dic, Map synonims)
  9. replaceVariable(final String src, final Map value)