java - 替换字符串中的多个子字符串,Array vs HashMap

标签 java arrays hashmap

下面定义了 2 个函数。它们执行完全相同的功能,即输入一个模板(其中想要替换一些子字符串)和字符串值数组(要替换的键值对,例如:[subStrToReplace1,value1,subStrToReplace1,value2,.....] ) 并返回替换后的字符串。

在第二个函数中,我迭代模板的单词并搜索相关键(如果存在于 HashMap 中),然后搜索下一个单词。如果我想用一些 substring 替换单词,并且我再次想用值中的其他键替换它,我需要迭代模板两次。我就是这么做的。

我想知道我应该使用哪一个以及为什么?任何比这些更好的替代方案也是受欢迎的。

第一个功能

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

第二个功能

public static String populateTemplate2(String template, String... values) {
    HashMap<String, String> map = new HashMap<>();
    for (int i = 0; i < values.length; i += 2) {
        map.put(values[i],values[i+1]);
    }
    StringBuilder regex = new StringBuilder();
    boolean first = true;
    for (String word : map.keySet()) {
        if (first) {
            first = false;
        } else {
            regex.append('|');
        }
        regex.append(Pattern.quote(word));
    }
    Pattern pattern = Pattern.compile(regex.toString());

    int N0OfIterationOverTemplate =2;
    // Pattern allowing to extract only the words
    // Pattern pattern = Pattern.compile("\\w+");
    StringBuilder populatedTemplate=new StringBuilder();;

    String temp_template=template;

    while(N0OfIterationOverTemplate!=0){
        populatedTemplate = new StringBuilder();
        Matcher matcher = pattern.matcher(temp_template);
        int fromIndex = 0;
        while (matcher.find(fromIndex)) {
            // The start index of the current word
            int startIdx = matcher.start();
            if (fromIndex < startIdx) {
                // Add what we have between two words
                populatedTemplate.append(temp_template, fromIndex, startIdx);
            }
            // The current word
            String word = matcher.group();
            // Replace the word by itself or what we have in the map
            // populatedTemplate.append(map.getOrDefault(word, word));

            if (map.get(word) == null) {
                populatedTemplate.append(word);
            }
            else {
                populatedTemplate.append(map.get(word));
            }

            // Start the next find from the end index of the current word
            fromIndex = matcher.end();
        }
        if (fromIndex < temp_template.length()) {
            // Add the remaining sub String
            populatedTemplate.append(temp_template, fromIndex, temp_template.length());
        }

        N0OfIterationOverTemplate--;
        temp_template=populatedTemplate.toString();
    }
    return populatedTemplate.toString();
}

最佳答案

绝对是第一个,至少有两个原因:

  1. 它更容易阅读且更短,因此更容易维护,因为它更不容易出错
  2. 您不依赖正则表达式,因此速度更快

关于java - 替换字符串中的多个子字符串,Array vs HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37323704/

相关文章:

java - ASM 如何在复制操作数堆栈(DUP_X1 和 DUP 操作数)时检查最大堆栈大小

java - 从 Android studio 导入项目时出现 Intellij Idea 错误

Javascript变量在更改后修复最后一个值

jquery - 如何使用jquery将序列化字符串转换为数组

java - 对 HashMap 键进行排序并存储在 ArrayList 中

Java 和 HashMap - 如何添加现有值?

java - Android:内存/资源泄漏

java - 实现高效的 512 位整数类型

数组 : why cannot use an array defined by indirectly computed const var in function begin(array)? 的 C++ 指针

java - hashmap如何处理负hashcode?