Search code examples
javastringdictionaryreplacestr-replace

Replacing a set substrings in a string independently (parallel)


// The array of values is in the form { "var1", "val1", "var2", "val2",.. }

 public static String replaceMethod(String template, String... values) {
            String p = template;
            for (int i = 0; i < values.length; i += 2) {
                p = p.replace(values[i], values[i+1]);
            }

            return populatedTemplate;    
        }

This method replaces a set of sub-strings with respectives values in a string. Ex:- string => abcd sub-string array of values ["a","b","c","d"] It means replace 'a' with 'b' and 'b' with 'c'.

So, now comes the issue.

1.My above implementation replaces 'a' with 'b' in first loop and then in second loop, it replaces 'b' with 'c' , making final string as "cccd". But I want the out as "bccd". Replacement in series uses the previous replaced string to work further. Is there a way to parallel replace all the sub-strings in a more efficient way.

2.How can I implement above method using Map, instead of array (second argument of above method)? Is Map better, or above implementation is fine ?


Solution

  • You better use a map and iterate over every character in template. This way you avoid multiple substitutions at the same index position.

    String template = "abcd";
    StringBuilder populatedTemplate = new StringBuilder();
    HashMap<Character, Character> map = new HashMap<>();
    map.put('a', 'b');
    map.put('b', 'c');
    for (int i = 0; i < template.length(); i++) {
        populatedTemplate.append(
                map.getOrDefault(template.charAt(i), template.charAt(i)));
    }
    System.out.println(populatedTemplate);
    

    Some pro arguments of this solution compared to OPs posted solution.

    • avoid multiple substitutions at the same index position, replace in a first step a to b and in a second step b to c which would lead into an unexpected effective replacement of a to c
    • iterate only once over template
    • don't create for each replacement pair a new String object, as it would have been here p = p.replace(values[i], values[i+1]);