[英]replace array value with hashmap values
HashMap<String, String> apos = new HashMap<String, String>();
apos.put("i'm","I am");
apos.put("can't","cannot");
apos.put("couldn't","could not");
String[] st = new String[]{"i'm","johny"};
Iterator itr = apos.entrySet().iterator();
for (int i = 0; i < st.length; i++) {
while((itr).hasNext()) {
if (itr.equals(st[i]))
{
st[i].replace(st[i],??????(value of the matched key))
}
}
}
我想將一個字符串與哈希映射進行比較,如果一個單詞與其鍵匹配,則將一個單詞替換為哈希映射值。 以上是我正在嘗試做的事情。 任何人都可以請幫我代替鑰匙寫些什么。
幫助將不勝感激。 謝謝
您無需遍歷地圖即可確定數組值是否為地圖中的鍵。 為此使用Map#containsKey()
方法。 因此,擺脫該迭代器。
if (map.containsKey(s[i]))
您根本不需要更換。 您可以簡單地使用=
運算符將新值分配給數組索引。
s[i] = newValue;
若要從映射中獲取要在數組中設置的特定鍵的值,請使用Map#get(Object)
方法。
map.get(s[i]);
試試看:代替st[i].replace(st[i],??????(value of the matched key))
采用
if(st[i].equals((String)itr.getKey()))
st[i] = (String)itr.getValue();
有關用法的詳細信息,請參閱本教程 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.