Replacing characters in a string based on mapping two sets of characters in Java -
i have edited 2 strings , can covert them character maps. trying think through best way map , replace based off of these 2 strings. example: have word append front of alphabet based on user input. in example cat(catdefghijkl..). take sentence , replace characters in based on new alphabet. (now c, b a, c t). not looking code input on best way accomplish this. can map 2 strings or character maps , replace based on mappings?
you can use map<character, character>
.
the key regular alphabet letter, , value new letter.
map<character, character> newalphabet = new hashmap<>(); list<character> regularalphabet = arrays.aslist('a', 'b', 'c');//put complete alphabet here public void updatealphabet(list<character> newletters) { assert (newletters.size() == 26);//or 52 uppercase atomicinteger = new atomicinteger(0); newalphabet.clear(); regularalphabet.stream() .foreach(letter -> newalphabet.put(letter, newletters.get(i.getandincrement()))); } public string replacestring(string s) { stringbuilder sb = new stringbuilder(); s.chars().foreach(c -> sb.append(newalphabet.get((char) c))); return sb.tostring(); }
please note, code not thread safe. testing out idea of using map map regular alphabet decoded alphabet.
could map 2 alphabet strings using hashmap?
if goal replace whole string replacement strings possible. use map<string, string>
store mappings. can use string's replaceall
method find initial string , replace new string.
//the key represents string need replaced value string map<string, string> stringmapping = new hashmap<>(); public string replacestring(string s) { (map.entry<string, string> entry : stringmapping.entryset()) { s = s.replace(entry.getkey(), entry.getvalue()); } return s; }
Comments
Post a Comment