【问题标题】:Splitting String and retrieving values by key from a HashMap拆分字符串并从 HashMap 中按键检索值
【发布时间】:2017-08-29 18:24:48
【问题描述】:

我遇到了一个问题,我需要将单词的缩写及其完整形式放入 hashmap。然后我需要制作一个程序来询问你的单词,然后为你打印地图上的完整单词。我可以用一个词来完成,但问题是当它询问许多带有字符串的键时。

例如:

给定单词:

tran. all of the wo. f. me

// 至此,我已经将所有带点的单词作为键值放到了 hashmap 中,并将它们的完整形式作为值。现在它应该将 Given words 打印为完整版本,其中虚线单词被替换为值。

完整版:

translate all of the words for me

当你在一个句子中被问到多个键时,如何打印所有被问到的值?

// 我认为我应该使用 .split 来完成这项工作,但我不确定它是如何工作的。

感谢您的帮助!

【问题讨论】:

  • 你的问题是......
  • @SimpsonD 这里有很多人愿意提供帮助,只要让他们容易理解您的问题。
  • 我正在尽力而为。问题:当你在一个句子中被问到多个键时,如何打印所有被问到的值。

标签: java string hashmap


【解决方案1】:

您应该使用split() 方法来获取所有输入的单词并将它们存储在String[] 中,然后遍历这些单词并尝试通过它们各自的值从您的地图中更改它们。

您的代码将是这样的:

Map<String, String> abbrev = new HashMap<String, String>();

String str="tran. all of the wo. f. me";
String[] words = str.split(" ");
String result = "";

for (String word : words) {
    if(abbrev.get(word) != null){
        result= result+ abbrev.get(word);
    }else{
        result= result+ word;
    }
    result= result+ " ";
}

注意:

请注意,您可以使用StringBuilder 作为构建结果String 的最佳方法。

演示:

这是working DEMO

【讨论】:

    【解决方案2】:

    我想这就是你的意思:

    String yourString = "tran. all of the wo. f. me";
    
    for(String word : yourString.split("\\s+"))
      System.out.println(map.get(word));
    

    Split 用于从字符串中获取每个单词,以空格分隔。

    【讨论】:

      【解决方案3】:

      有很多方法可以实现您的目标。其中之一如下:

           Map<String, String> map = new HashMap<>();
           map.put("tran", "translate");
           map.put("wo", "words");
           map.put("f", "for");
      
           String word = "tran. all of the wo. f. me";
           String[] words = word.split(" ");
           for(int i=0;i<words.length;i++) {
               if(words[i].endsWith(".")) {
                   words[i] = map.get(words[i].substring(0, words[i].length() - 1));
               }
           }
           word = String.join(" ", words);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-23
        • 1970-01-01
        • 2013-10-22
        • 2018-11-06
        • 1970-01-01
        • 2020-12-01
        • 2021-12-16
        相关资源
        最近更新 更多