6

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.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • Related question: http://stackoverflow.com/questions/187676/java-equivalents-of-c-sharp-string-format-and-string-join?rq=1 – Möoz Apr 16 '14 at 00:26
  • possible duplicate of [Java Equivalent to .NET's String.Format](http://stackoverflow.com/questions/3754597/java-equivalent-to-nets-string-format) – Möoz Apr 16 '14 at 00:27

4 Answers4

8

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.

laz
  • 28,320
  • 5
  • 53
  • 50
6

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

James
  • 12,636
  • 12
  • 67
  • 104
  • 2
    This answer is not complete. This is not the direct replacement. {0} and {1} in .NET are there so that they define the location of the parameters. For example it could be "Test: {1}, {0}", so %s, %s would replace wrong locations. – frankish Mar 22 '13 at 23:36
4
String.format("Test: %s, %s",string1,string2)
dfb
  • 13,133
  • 2
  • 31
  • 52
0
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");
Jester
  • 56,577
  • 4
  • 81
  • 125
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
  • It looks a lot longer than spinning_plate's method, what is its difference? – Luke Vo Jul 21 '11 at 00:41
  • It's the same result, although Formatter I believe can do a lot more but I would go with his method I just wanted to show some other ones in case you were doing different types of formatting. – Jesus Ramos Jul 21 '11 at 00:44