2017-04-04 69 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);