我的字符串看起来像;
String values = "I am from UK, and you are from FR";
和我的哈希表;
Hashtable countries = new Hashtable();
countries.put("United Kingdom", new String("UK"));
countries.put("France", new String("FR"));
用哈希表中的值相应地更改我的字符串中的值的最有效方法是什么。这些只是要更改的 2 个值,但在我的情况下,我将有 100+
最佳答案
我不确定您是否可以做很多事情来以有值(value)的方式对其进行优化。实际上,您可以为这样的自定义替换构建 FSM,但这可能比您真正想要的要多。
Map<String, String> countries = new HashMap<String, String>();
countries.put("United Kingdom", "UK");
countries.put("France", "FR");
for (Map.Entry<String, String> entry : countries.entrySet()) {
values.replace(entry.getKey(), entry.getValue());
}
一些注意事项:
不要使用
Hashtable
.使用Map
(接口(interface))和HashMap
(类)代替;在适用的情况下,将您的变量、参数和返回类型声明为接口(interface)而非具体类;
假设您使用的是 Java 5,请使用泛型类型参数以获得更具可读性的代码。在这种情况下,
Map<String, String>
, ETC;和不要使用
new String("UK")
.没有必要。
关于java - 从 Java 中的哈希表替换字符串中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2987898/