I have a string which has certain “tokens”.
Example:
"Someone e.g. X here is a # and the other i.e. X is not but over is something else like #"
I also have a list of String e.g. {"John", "doctor", "Jim","engineer"}
What is the best way to do the following:
I want to replace all the # characters with the corresponding element in the list.
I.e. I want to skip X and John and replace Jim from # and engineer for the other #.
I thought to just loop over the string#toCharArray() but I was interested if there is a better way to do this.
Note: The values in the second list match the corresponding tokens. So the first value in the list i.e. John maps to the first occurence of X or # which ever that is.
Example:
Input: "Someone e.g. X here is a # and the other i.e. X is not but the other is something else like # but X is at least X but not #"
{"John", "doctor", "Jim","John", "engineer", "doctor"}
Output:
"Someone e.g. X here is a doctor and the other i.e. X is not but the other is something else like Jim but X is at least X but not doctor"
You might be interested to look at MessageFormat that allows something similar to this kind of replacement.
E.g.
Edit:
If the input string cannot be modified to include the placeholders and also the placeholders have special meaning as you mentioned in your update (i.e. X should be ignored, # should be replaced), then you just have to
StringBuilder.StringBuilderobject.counterfrom the input array and append that to theStringBuilderobject.StringBuilder.toString()and trim to remove the trailing space.