What is the best way to replace 'gift' and 'price' from below string using java-
We’ve added {gift} coupon worth {price}. Enjoy!
Also can i use MessageFormat in any way to solve above problem.
What is the best way to replace 'gift' and 'price' from below string using java-
We’ve added {gift} coupon worth {price}. Enjoy!
Also can i use MessageFormat in any way to solve above problem.
Something like the below works:
String str = "We’ve added {gift} coupon worth {price}. Enjoy!";
System.out.println(str);
str = str.replace("{gift}", "unicorns");
str = str.replace("{price}", "$399");
System.out.println(str);
You can't use a MessageFormat to replace text in the input String
you've provided, but if you save your String
as a format to use it MessageFormat, it makes it a lot easier to read:
String defaultFormat = "We’ve added {0} coupon worth {1}. Enjoy!";
String defaultOutput = MessageFormat.format(defaultFormat, "unicorns", "$399");
System.out.println(defaultOutput);
defaultOutput = MessageFormat.format(defaultFormat, "leprechaun", "$199");
System.out.println(defaultOutput);
String yodaOutput = MessageFormat.format("coupon worth {1} we have added for {0}. Enjoy!", "unicorns", "$399");
System.out.println(yodaOutput);