Equivalent to String.Format (.NET) in Java?

String.Format in .NET (maybe just VB.NET) converts {0}, {1}, ... to a specific string, for example:

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

I tried to search on Google and StackOverflow, but they all return a numeric string format.

+6
source share
4 answers

Other suggestions are certainly good, but more in the style of printf and its lines, which are later additions to Java. The code you posted looks inspired by MessageFormat .

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

I'm not sure what the 'Return: operator does.

+8
source

Use MessageFormat.format , you can also specify formatting arguments in 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, you can use String.format , but this does not guarantee a position, for example. String.format("What do you get if you multiply %d by %s?", varNumber, varText); .

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

Source: https://habr.com/ru/post/893220/


All Articles