2017-04-04 70 views
-2

我遇到了一个问题,需要将单词的缩写及其完整形式放入hashmap中。然后,我需要制作一个程序,向您询问单词,然后从地图上为您打印完整单词。我可以用一个字来完成,但问题在于何时用字符串询问很多键。分割字符串并通过HashMap中的键值检索值

例如:

给出的单词:

tran. all of the wo. f. me 

//在这一点上我已经把所有的与点的话作为HashMap的键值,他们的充分形式值。现在它应该打印给定的单词作为完整版本,其中虚线单词被替换为值。

完整版:

translate all of the words for me 

当你被要求多个键一句话,如何打印所有要求的价值观呢?

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

谢谢你的帮助!

+4

,你的问题是.... – Andres

+0

@SimpsonD有很多人愿意帮助在这里,只要你的问题容易让他们理解。 – Eugene

+0

我在尽我所能。问题:当你在一个句子中被询问多个键时,如何打印所有要求的值。 – SimpsonD

回答

0

您应该使用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

DEMO:

这是一个working DEMO

0

我想这就是你的意思:

String yourString = "tran. all of the wo. f. me"; 

for(String word : yourString.split("\\s+")) 
    System.out.println(map.get(word)); 

斯普利特用于从字符串得到的每一个字,用空格隔开。

0

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

 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);