Search code examples
javastringreplacejava-6

String Replace problem


What I have:

I've got a text "Hi {0}, my name is {1}."

I've got a List<String> names = Arrays.asList("Peter", "Josh");

I'm trying to fit Peter where there's a {0} and Josh where there's a {1}.

What I want:

Hi Peter, my name is Josh.

Any ideas of how could I do it?


Solution

  • Probably simplest would be to use one of the String.replaceXX ops in a loop. Eg,

    String sourceString = "Hi {1}, my name is {2}."
    for (i = 0; i < names.size(); i++) {
        String repText = names.get(i);
        sourceString = sourceString.replace("{" + (i+1) + "}", repText);
    }
    

    This is a bit inefficient, since it's bad form to repeatedly create new Strings vs using a StringBuffer or some such, but generally text replacement of this form would be a low-frequency operation, so simplicity trumps efficiency.