简体   繁体   English

Java 中的 String.Format (.NET) 等效项?

[英]String.Format (.NET) equivalent in Java?

The String.Format in .NET (maybe just VB.NET) convert {0}, {1}, ... into determined String, for example: .NET(可能只是VB.NET)中的String.Format将{0},{1},...转换为确定的String,例如:

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.我尝试在 Google 和 StackOverflows 中搜索,但它们都返回数字字符串格式。

The other suggestions are certainly good, but are more in the style of printf and its lineage which are more recent additions to Java.其他建议当然很好,但更多的是printf及其谱系,这是 Java 的最新添加。 The code you posted looks to be inspired by MessageFormat .您发布的代码看起来受到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.我不确定'Return:语句在做什么。

Use MessageFormat.format , you can also provide formatting arguments in the replacement tokens.使用MessageFormat.format ,您还可以在替换令牌中提供格式化 arguments 。

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 eg String.format("What do you get if you multiply %d by %s?", varNumber, varText);或者,可以使用String.format ,但这并不能保证 position 例如String.format("What do you get if you multiply %d by %s?", varNumber, varText); . .

String.format("Test: %s, %s",string1,string2)
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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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