Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Equivalent to .NET's String.Format

Tags:

java

string

c#

.net

Is there an equivalent to .NET's String.Format in Java?

like image 798
BuddyJoe Avatar asked Sep 20 '10 19:09

BuddyJoe


People also ask

What is %- 5d in Java?

"%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate. "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.

Is there a .format in Java?

Java String format() The java string format() method returns the formatted string by given locale, format and arguments. If you don't specify the locale in String. format() method, it uses default locale by calling Locale.

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

Does Java have formatted string?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.


2 Answers

The 10 cent answer to this is:

C#'s

 String.Format("{0} -- {1} -- {2}", ob1, ob2, ob3) 

is equivalent to Java's

 String.format("%1$s -- %2$s -- %3$s", ob1, ob2, ob3) 

Note the 1-based index, and the "s" means to convert to string using .toString(). There are many other conversions available and formatting options:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

like image 67
Oscar Boykin Avatar answered Sep 19 '22 17:09

Oscar Boykin


Have a look at the String.format and PrintStream.format methods.

Both are based on the java.util.Formatter class.

String.format example:

Calendar c = new GregorianCalendar(1995, MAY, 23); String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); // -> s == "Duke's Birthday: May 23, 1995" 

System.out.format example:

// Writes a formatted string to System.out. System.out.format("Local time: %tT", Calendar.getInstance()); // -> "Local time: 13:34:18" 
like image 34
dtb Avatar answered Sep 22 '22 17:09

dtb