This is the simple algorithm to replace all the keys from sentence with some values.
Here I am going to use StringBuilder to rebuild new string and It will going to take O(n), Here n is a number of characters in sentence.
Input :
String s = “Hi %NAME%, This is the great mail example, You got 10% discount on %ITEM%, Thanks for shopping with %COMPANY%,”
Here we have to replace three keys (%NAME% , %COMPANY% amd %ITEM%) with some values.
For example we have below map :
map.put("NAME", "Dhiral Pandya"); map.put("ITEM", "Computer"); map.put("COMPANY", "omtlab");
Output :
Hi Dhiral Pandya, This is the great mail example, You got 10% discount on Computer, Thanks for shopping with omtlab,
Algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package com.omt.learn.algo; import java.util.Map; import java.util.TreeMap; public class ReplaceKeyWithValueString { public static void main(String[] args) { String s = "Hi %NAME%, " + "This is the great mail example, " + "You got 10% discount on %ITEM%, " + "Thanks for shopping with %COMPANY%,"; // Here we have to replace three keys (%NAME% , %COMPANY% amd %ITEM% // with some values.) // NOTE : DO NOT USE replace function of string to do this. Map<String, String> map = new TreeMap<>(); map.put("NAME", "Dhiral Pandya"); map.put("ITEM", "Computer"); map.put("COMPANY", "omtlab"); System.out.println(replaceKeyWithValues(map, s)); } public static String replaceKeyWithValues(Map<String, String> keyValue, String s) { StringBuilder sb = new StringBuilder(); int index = 0; boolean start = false; StringBuilder word = new StringBuilder(); while (index < s.length()) { if (s.charAt(index) == '%') { if (start) { if (keyValue.containsKey(word.toString())) { start = false; sb.append(keyValue.get(word.toString())); } else { sb.append("%" + word.toString()); } word.setLength(0); } else { start = true; } } else { if (start) { word.append(s.charAt(index)); } else { sb.append(s.charAt(index)); } } index++; } return sb.toString(); } } |