简体   繁体   中英

Java String not replacing with hashmap values

   for (Entry<String, String> entry : map.entrySet()) {

                String delimiter = "**";
                result = result.replace(delimiter + entry.getKey() + delimiter, entry.getValue());

            }

result is my string to be replaced by hashmap values. Here string (result variable) is returning as itself not replacing any value. Please any one have suggestions ?


From comment

My hashmap contains,

HashMap<String, String> map = new HashMap<String, String>(); 
map.put("Rid", serviceBooking.getId().toString()); 
map.put("Rname", customer.getName()); 
map.put("Rnic", "");

Either your HashMap is empty, or the original string doesn't contain anything corresponding to the keys in the map, or you wrote two asterisks where you meant one, or you didn't escape it/them when you needed to, or ...

Impossible to improve on that without seeing the original string and the contents of the map.

The algorithm OK Here's a working, executable example:

// sample input
String input = "abcd **Rid** efgh";

// a small map
Map<String, String> map = new HashMap<String, String>();
map.put("Rid","VALUE");

// the loop that replaces the **Rid** substring
for (Map.Entry<String,String> entry:map.entrySet()){
  input = input.replace("**"+entry.getKey()+"**", entry.getValue());
  System.out.println(input);
}

It prints

abcd VALUE efgh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM