2017-10-09 52 views
1

我有一个HashMap<Integer, Double>看起来类似这样的: {260 = 223.118,50,261 = 1889,00,262 = 305,70,270 = 308,00}替换某些串的值动态

从数据库中,我有一个字符串,可能是这个样子: 字符串结果= “(260 + 261) - (262 + 270)”;

我想改变字符串的值260,261,262 ...(它们总是与HashMap的键相同)与值,所以我可以得到一个字符串: String finRes =“(223.118, 50 + 1889,00) - (305,70 + 308,00)“;

而且字符串的结果能够包含乘法和除法的字符。这里

+0

那你试试?为什么数学表达式存储在数据库中(而不是结果) – 2017-10-09 16:25:13

+0

这是非常复杂的解释,对不起。上面的解释是足够的,下面的答案似乎是非常有前途的。我将尽快对代码进行测试。 –

回答

1

一个简单的正则表达式的解决办法是你输入的字符串与模式匹配(\d+)。这应该产生算术字符串中的所有整数。然后,我们可以在映射中查找每个匹配,转换为一个整数,以获得相应的double值。由于所需的输出又是一个字符串,我们必须将双精度转换回字符串。

Map<Integer, Double> map = new HashMap<>(); 
map.put(260, 223.118); 
map.put(261, 1889.00); 
map.put(262, 305.70); 
map.put(270, 308.00); 

String input = "(260+261)-(262+270)"; 
String result = input; 
String pattern = "(\\d+)"; 

Pattern r = Pattern.compile(pattern); 
Matcher m = r.matcher(input); 
StringBuffer sb = new StringBuffer(); 

while (m.find()) { 
    m.appendReplacement(sb, String.valueOf(map.get(Integer.parseInt(m.group(1))))); 
} 
m.appendTail(sb); 
System.out.println(sb.toString()); 

输出:

(223.118+1889.0)-(305.7+308.0) 

演示这里:

Rextester

0

这里是一个说明的解决方案:

// your hashmap that contains data 
    HashMap<Integer,Double> myHashMap = new HashMap<Integer,Double>(); 
    // fill your hashmap with data .. 
    .. 
    // the string coming from the Database 
    String result = "(260+261)-(262+270)"; 
    // u will iterate all the keys of your map and replace each key by its value 
    for(Integer n : myHashMap.keySet()) { 
     result = result.replace(n,Double.toString(myHashMap.get(n))); 
    } 
    // the String variable 'result' will contains the new String 

希望它能帮助:)

+0

这可能会导致一些“哦,不!”例如,如果字符串包含160和地图有一个16键 – 2017-10-09 16:30:54

+0

是的,我用U @RC议员的意见。 ..,我没有想到这种情况下,所以答案必须删除:),一般来说,我认为他必须先尝试编码,然后发布问题以获得更好的解决方案 –