Reputation: 25
I have a HashMap<Integer, Double>
which looks something similar like this:
{260=223.118,50, 261=1889,00, 262=305,70, 270=308,00}
From database I take a string that could look something like this: String result = "(260+261)-(262+270)";
I want to change the string's values of 260, 261, 262... (which are always the same with the HashMap's keys) with the values so I could get a string like: String finRes = "(223.118,50+1889,00)-(305,70+308,00)";
Also the string result can contain multiplication and division characters.
Upvotes: 1
Views: 156
Reputation: 522254
A simple regex solution here would be to match your input string against the pattern (\d+)
. This should yield all the integers in the arithmetic string. Then, we can lookup each match, converted to an integer, in the map to obtain the corresponding double value. Since the desired output is again a string, we have to convert the double back to a string.
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());
Output:
(223.118+1889.0)-(305.7+308.0)
Demo here:
Upvotes: 1
Reputation: 3297
here is an explained solution:
// 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
Hope it helps :)
Upvotes: 0