我有一堆字符串,其中包含一些应该用图像替换的特定标记。所以起初我用标记和图像创建了哈希图:
Map<String, String> images = new HashMap<String, String>();
images.put(":img:howdy:", "path/images/hello.png");
images.put(":img:code:", "path/images/code.png");
images.put(":img:smile:", "path/images/sm.png");
//...and 70 more records
字符串看起来像:
这是一个字符串 :img:howdy:,你知道的 :img:smile:
甚至更多:img:smile:
这是一个带有图像的字符串:img:code::img:smile:
解析后,所有标记都计划用图像替换。
我坚持以下几点:
Map<String, String> images = new HashMap<String, String>();
images.put(":img:howdy:", "path/images/hello.png");
images.put(":img:code:", "path/images/code.png");
images.put(":img:smile:", "path/images/sm.png");
String[] strings = {"This is a string :img:howdy:, you know it :img:smile:",
"And even more:img:smile:",
"This is a string with images:img:code::img:smile:"};
for (String text : images.keySet()) {
for (String string : strings) {
if(string.contains(text)) {
string.replace(text, images.get(text));
}
}
}
首先,标记被替换,但有很多迭代。其次,如果我使用,例如,StringBuilder,我有很多重复,一些标记被替换,一些没有。
我不擅长字符串解析和相应的算法(目前),所以在查看我选择的方法后不要向我扔石头。
按照 Dariusz Waver 的建议,添加 了一些 Reworked,这就是我所拥有的:
private final String IMAGE_PATTERN = ":s:\\w+:";
//.......
Pattern p = Pattern.compile(IMAGE_PATTERN);
Matcher m = p.matcher(message);
while(m.find())
{
String imgPattern = message.substring(m.start(), m.end());
String imgPath = ImgPaths.images.get(imgPattern);
//If there's no such image in Images Map
if(imgPattern != null) {
message = message.replace(imgPattern, imgPath);
m.reset(message);
}
}
StringBuilder result = new StringBuilder();
result.append(timestamp).append(" - ").append(sender)
.append(": ").append(message);
考虑到文本量非常大,有什么方法可以使其更加优化?