简体   繁体   中英

String format - java

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM