gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:22:26 27 4
gpt4 key购买 nike

下面定义了 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com