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?
MessageFormat class is your friend. http://download.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html
String aa = "Hi {0}, my name is {1}";
Object[] bb = {"Peter" , "John"};
System.out.println(MessageFormat.format(aa, bb));
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.
List<String> names = new ArrayList<String();
names.add("Peter");
names.add("Josh");
String str = "Hi {1}, my name is {2}.";
str = str.replaceFirst("{1}", names.get(0));
str = str.replaceFirst("{2}", names.get(1));
String text = "Hi {1}, my name is {2}.";
java.util.List<String> names = Arrays.asList("Peter", "Josh");
for(String s: names) text = text.replace("{" + (names.indexOf(s) + 1) + "}", s);
You would do something like this.
List<String> names = Arrays.asList("Peter", "Josh");
System.out.printf("Hi %s, my name is %s.", names.get(0), names.get(1));
and that would be it in just 2 lines of code.
List<String> names = new ArrayList<String>();
names.add("Peter");
names.add("Josh");
System.out.println("Hi " + names.get(0) + ", my name is " + names.get(1) + ".");
My apologies if I'm taking you too literally and you wanat something more generic but this will do exactly as you asked.
I'm assuming that your list will have the correct number of elements.
`String s = "Hi {1}, my name is {2}.";`
for(int x = 1;x <= names.size();x++)
{
s.replaceFirst("{" + x +"}",names.get(x - 1));
}
精彩评论