I have written a code to check if a string has the key in a give Map and replace the key with the value in the string.
Below is the code
String s ="VamshiKrishnaA";
Map<String,String> h = new HashMap<String,String>();
h.put("Vamshi", "89");
h.put("VamshiKrishnaA","dataDir");
h.put("VamshiKrishna","dataDira");
h.put("VamshiK", "krihsn");
String key="";
Iterator<String> i =h.keySet().iterator();
while(i.hasNext()){
key=i.next();
if(s.contains(key)){
s=s.replace(key, h.get(key));
}
}
System.out.println(s);
When i run the above code, i got the output as dataDiraA but i need output to be dataDir.
I dont have control over the order of the key and values it is autogenerated.
Need any help in this regard
You need to track the length of the currently matched key, and only use the one which is the longest: