How to format strings in Java
In addition to String.format, also take a look java.text.MessageFormat
. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.
For example:
int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));
A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:
MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");
MessageFormat
is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:
String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });
What's the difference between String.format() and str.formatted() in Java?
Make sure you use a good IDE so that you have easy access to browse into JDK source code. In Eclipse say, use F3 to open to any declaration. IntelliJ IDEA has similar feature.
If you view the source code for both methods, you can see these calls are identical except that variables this
is interchanged with format
when comparing the instance vs static method:
public String formatted(Object... args) {
return new Formatter().format(this, args).toString();
}
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
So as you've observed: String.format(str, args)
is same as str.formatted(args)
How Can I Correctly Format a String In Java?
You need to pass the values as arguments to String.format()
:
String.format("%02d:%02d:%02d", hour, minute, second)
How to format string output java
Like?
System.out.println("NAME TYPE LINE# ");
String[][] data = {{"a", "prod", "1"}, {"b", "prod", "2"}};
for (int i = 0; i < data.length; i++) {
System.out.println(String.format("%-5s %-5s %-5s", data[i][0], data[i][1], data[i][2]));
}
or if you prefer (within your Symbol
class):
@Override
public String toString() {
return String.format("%-5s %-5s %-5s", type, name, lineNum);
}
Java: how to format string with logging-like pattern?
If you using slf4j
, you can use its MessageFormatter.arrayFormat
which returns a FormattingTuple
,
FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
And then convert it to a string.
String msg = ft.getMessage();
Which means you can add a utility method for that
static String format(String format,String...params){
FormattingTuple ft = MessageFormatter.arrayFormat(format,params);
String message = ft.getMessage();
return message;
}
System.out.println(format("hi {}, you {}","there","rock"));
How to build a formatted string in Java?
String s = String.format("x:%d, y:%d, z:%d", x, y, z);
Java Howto - Format a string
Format text with a list of argument in java
String.format()
take as parameters a format and array of Objects (vararg is an array of Objects behind the scene). All you need to do is to convert your list to array of Strings and pass that to String.format()
, like so:
public static void main(String args[]) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
String toFormat = "This is a first value %s, This is a second value %s";
String result = String.format (toFormat, list.toArray(new String[0]));
System.out.println(result);
}
Java Format string to C#
Starting from C# 6. you can use interpolation.
For your case you may wanted to try the following:
string formattedString = $"{0:d6} {7.1:f} {5.1:f}";
before C# 6 you can try the following:
string formattedString = String.Format("{0:d6} {1:f} {2:f}", 0, 7.1, 5.1);
How to format multiple string parameters in Java
To get formatting on each of them you need to pass them separately to printf
rather than combining them into one string with +
.
System.out.printf("%-30s %-30s %-30s", divName, heading1, heading2);
Related Topics
How to Set the Classpath in Netbeans
How to Create a Rest Client for Java
Are Static Fields Open for Garbage Collection
Static Method in a Generic Class
Regex for Matching Something If It Is Not Preceded by Something Else
How to Perform Mouseover Function in Selenium Webdriver Using Java
Differences in Boolean Operators: & VS && and | VS ||
Preferred Way of Loading Resources in Java
Difference in Days Between Two Dates in Java
Java Io Implementation of Unix/Linux "Tail -F"
How to Create a Jar with External Libraries Included in Eclipse
How to Write a Utf-8 File with Java
How to Make a Jar File That Includes Dll Files