Java Map Replace replaceAllOccurrences(String str, Map replacementMap)

Here you can find the source of replaceAllOccurrences(String str, Map replacementMap)

Description

replace All Occurrences

License

Open Source License

Declaration

public static String replaceAllOccurrences(String str, Map<String, String> replacementMap) 

Method Source Code

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

import java.util.*;

public class Main {
    public static String replaceAllOccurrences(String str, Map<String, String> replacementMap) {
        Set<Map.Entry<String, String>> entries = replacementMap.entrySet();
        Iterator<Map.Entry<String, String>> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            str = replaceOccurrences(str, entry.getKey(), entry.getValue());
        }/*from   ww  w .  ja va  2  s .c  om*/
        return str;
    }

    public static String replaceOccurrences(String str, String oldField, String newField) {
        if (str == null) {
            return null;
        }
        int ix = str.indexOf(oldField);
        if (ix < 0) {
            return str;
        }

        StringBuilder sb = new StringBuilder();
        int len = oldField.length();

        while (ix >= 0) {
            if (ix > 0) {
                sb.append(str.substring(0, ix));
            }
            sb.append(newField);
            str = str.substring(ix + len);
            ix = str.indexOf(oldField);
        }
        if (str.length() > 0) {
            sb.append(str);
        }
        return sb.toString();
    }

    public static int indexOf(String str, String substr) {
        if (str != null) {
            return str.indexOf(substr);
        } else {
            return -1;
        }
    }

    public static int indexOf(String str, String substr, int ix) {
        if (str != null) {
            return str.indexOf(substr, ix);
        } else {
            return -1;
        }
    }

    public static String substring(String str, int startIx) {
        return str.substring(startIx);
    }

    public static String substring(String str, int startIx, int endIx) {
        return str.substring(startIx, endIx);
    }
}

Related

  1. replace(String text, Map pairs)
  2. replace2(String str, Map data)
  3. replaceAll(Map globals, String value)
  4. replaceAll(String inTemplate, Map inVars)
  5. replaceAll(String template, Map variables)
  6. replaceAllRegex(String input, Map replacements)
  7. replaceByMap(String _searchStr, Map _replacements)
  8. replaceByMap(String tpl, Map map)
  9. replaceCharacters(String sequence, Map map, boolean reverse)