java - Avoid recursive replacement on a string -


assume there string:

"i'm boy." 

and synonyms words (in key-value format):

boy -> "male yong" yong -> "age under 18" 

if replace string synonyms words one one, be:

step 1, find word "boy" , replace it: "i'm male young." step 2, find word "young" , replace it: "i'm male age under 18." need not recursive replacement, need replace orginal string, in other words step 2 should find "young" in orginal string:"i'm boy." not "i'm male young." there simple solution:

firstly replace key %s , add synonyms word list:

string: "i'm %s" list: "male yong" 

then format string list:

string.format(string, list) 

it works fine stupid , slow, have more clear solution?

pseudo code (not tested , function names might wrong):

string[] arr = sentence.split(" "); stringbuilder sb = new stringbuilder(); //can specify size better results possibly  (string s :arr ){    if ( dic.contains(s) ){        sb.append(dic.get(s));    }else{        sb.append(s);    } }  sb.tostring();//your replaced string 

i not sure string.format internally might doing similar doubt performance boost.


Comments