[英]In Java, how do you loop through a string and check if it contains the keys in a hash map?
The goal is to write a text message abbreviation expander program that takes a string and checks for common abbreviations like LOL, IDK, etc. and replace them with the full length sentence, laugh out loud, I don't know, etc.目标是编写一个文本消息缩写扩展器程序,该程序接受一个字符串并检查 LOL、IDK 等常见缩写,并用全长句子替换它们,大声笑,我不知道等。
import java.util.HashMap;
import java.util.Scanner;
public class TextMsgExpander {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter text: ");
String userInput = scnr.nextLine();
System.out.println("You entered: " + userInput);
// Create new instance of Hash Map
HashMap<String, String> map = new HashMap<String, String>();
//Key value pairs
map.put("LOL", "laugh out loud");
map.put("IDK", "I don't know");
map.put("BFF", "best friend forever");
map.put("TTYL", "talk to you later");
map.put("JK", "just kidding");
map.put("TMI", "too much information");
map.put("IMHO", "in my humble opinion");
//Access points
String LOL = map.get("LOL");
String IDK = map.get("IDK");
String BFF = map.get("BFF");
String TTYL = map.get("TTYL");
String JK = map.get("JK");
String TMI = map.get("TMI");
String IMHO = map.get("IMHO");
System.out.println(TMI);
// While user input contains any of the keys, replace keys with
// values.
return;
}
}
You can instead iterate(loop) over the complete set of keys and look for them in the userInput
, if they are present replace them with the respective value from the map as :您可以改为迭代(循环)整个键集并在
userInput
查找它们,如果它们存在,则将它们替换为地图中的相应值:
for (Map.Entry<String, String> entry : map.entrySet()) {
if (userInput.contains(entry.getKey())) {
userInput = userInput.replaceAll(entry.getKey(), entry.getValue());
}
}
System.out.println("Converted string - " + userInput);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.