用其全貌替换缩写/俚语

时间:2017-01-16 10:28:42

标签: java string hashmap

我正在使用HashMap存储缩写的完整表单。

public class Test {
    public static void main(String[] args) {
        Map<String, String> slangs = new HashMap<String, String>();
        slangs.put("lol", "laugh out loud");
        slangs.put("r", " are ");
        slangs.put("n", " and ");
        slangs.put("idk", " I don't know ");
        slangs.put("u", " you ");
        Set set = slangs.entrySet();
        Iterator i = set.iterator();

        String sentence = "lol how are you";
        StringBuilder sb = new StringBuilder();

        for (String word : sentence.split(" ")) {
            while(i.hasNext()) {
                Map.Entry<String, String> me = (Map.Entry)i.next();
                if (word.equalsIgnoreCase(me.getKey())) {
                    sb.append(me.getValue());
                    continue;
                }
                sb.append(word);
            }
        }
        System.out.println(sb.toString());
    }
}

输出是:

lollollollaugh out loudlol

这里有什么问题,如何解决?

3 个答案:

答案 0 :(得分:5)

您不应该遍历条目以查找匹配项,您应该使用get(Object key)getOrDefault(Object key, V defaultValue)来获取给定缩写的完整形式,否则不要获取完整的表单时间复杂度为O(1)时,你会得到一个O(n),这在表现方面当然不好,你会失去在{{{ 1}}。如果您是因为这种情况而做的,只需将您的密钥仅以小写字母放在地图中,然后使用小写字母调用Mapget,如下所示:

所以你的循环应该是这样的:

getOrDefault

<强>输出:

for (String word : sentence.split(" ")) {
    // Get the full form of the value of word in lower case otherwise use
    // the word itself
    sb.append(slangs.getOrDefault(word.toLowerCase(), String.format(" %s", word)));
}

使用Stream API,它可能只是:

laugh out loud how are you

答案 1 :(得分:3)

不要遍历字典中的键。相反,只需检查键是否在地图中并获取相应的值。另外,不要忘记将空格添加回组合句子。

for (String word : sentence.split(" ")) {
    if (slangs.containsKey(word.toLowerCase())) {
        sb.append(slangs.get(word.toLowerCase()));
    } else {
        sb.append(word);
    }
    sb.append(" ");
}

如果您使用的是Java 8,还可以使用String.joinMap.getOrDefault和Streams:

String s = String.join(" ", Stream.of(sentence.split(" "))
        .map(word -> slangs.getOrDefault(word.toLowerCase(), word))
        .toArray(n -> new String[n]));

后一种方法的好处是不会在句子的第一个词之后或之后添加空格。

答案 2 :(得分:0)

简单地说,我认为您只需要检查slangs是否包含此关键字。 请检查我的代码。

 public class Test {
    public static void main(String[] args) {

      Map<String, String> slangs = new HashMap<String, String>();
      slangs.put("lol", "laugh out loud");
      slangs.put("r", " are ");
      slangs.put("n", " and ");
      slangs.put("idk", " I don't know ");
      slangs.put("u", " you ");

      String sentence = "lol how are you";
      String[] words = sentence.split(" ");

      for (String word : words) {
        String normalizeWord = word.trim().toLowerCase();
        if(slangs.containsKey(normalizeWord)) {
            sentence = sentence.replace(word, slangs.get(normalizeWord));
        }
    }
    System.out.println(sentence);
  }
}