java - string manipulation : insert words at certain indexes in string, simultaneously -
i have searched lot couldn't find allow me insert words @ indexes simultaneously. example : have string :
rock climbing fun, love rock climbing.
i have hashmap words indicate index in string : e.g. :
rock -> 0,29 climbing -> 5,34 fun -> 17
now question : want put [start] tag @ start of these words , [end] tag @ end of them, in string. can't 1 one since in case once insert [start] @ index 0, other indexes modified , i'll have recalculate them. there way in can insert of tags @ once or something? can suggest other solution problem?
i can't use regular expressions(replaceall method), since i'll have sentence :
rocks hard.
and hashmap :
rock -> 0
i looking faster solutions here.
edit : sentence :
rocks hard frocks beautiful. rocks -> 0
here don't want replace frocks tags.
this not doing want, consider alternative solution tries achieve goal via different means.
i suppose 2 different things, firstly, suppose there exists list<string> words
, contains words want replace.
then code be:
public string inserttags(final string input) { (string word : words) { input.replace(word, "[start]" + word + "[end]"); } return input; }
second case, closer example not using indices, suppose there exists map<string, list<integer>>
, contains words , indices replaces them @ in list representation.
then code be:
public string inserttags(final string input) { (map.entry<string, list<integer>> entry : words.entryset()) { string word = entry.getkey(); input.replace(word, "[start]" + word + "[end]"); } return input; }
the latter definately more complex , not use indices, preferably should rewrite former.
hope helps without having worry indices.
Comments
Post a Comment