String.Format (.NET) equivalent in Java?

≯℡__Kan透↙ 提交于 2019-12-07 02:20:08

问题


The String.Format in .NET (maybe just VB.NET) convert {0}, {1}, ... into determined String, for example:

Dim St As String = "Test: {0}, {1}"
Console.WriteLine(String.Format(St, "Text1", "Text2"))

I've tried to search in both Google and StackOverflows, but they all return number-string format.


回答1:


The other suggestions are certainly good, but are more in the style of printf and its lineage which are more recent additions to Java. The code you posted looks to be inspired by MessageFormat.

String format = "Test: {0}, {1}"
System.out.println(MessageFormat.format(format, "Text1", "Text2"))

I'm not really certain about what the 'Return: statement is doing though.




回答2:


Use MessageFormat.format, you can also provide formatting arguments in the replacement tokens.

message = MessageFormat.format("This is a formatted percentage " +
                "{0,number,percent} and a string {1}", varNumber, varText);
        System.out.println(message);

message = MessageFormat.format("This is a formatted {0, number,#.##} " +
                "and {1, number,#.##} numbers", 25.7575, 75.2525);
        System.out.println(message);

Alternatively, String.format can be used but this doesn't guarantee position e.g. String.format("What do you get if you multiply %d by %s?", varNumber, varText);.




回答3:


String.format("Test: %s, %s",string1,string2)



回答4:


System.out.printf()
System.out.format()

For other methods use:

StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb, Locale.US);
f.format("my %s", "string");


来源:https://stackoverflow.com/questions/6770126/string-format-net-equivalent-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!