杰瑞科技汇

Java中string.format如何使用?

Of course! The phrase "string.format java" almost always refers to Java's String.format() method and its associated printf() style formatting. This is the standard way to create formatted strings in Java, similar to the famous printf function in C.

Java中string.format如何使用?-图1
(图片来源网络,侵删)

Here’s a complete guide covering everything you need to know.


The String.format() Method

The String.format() method is a static utility that returns a formatted string using the specified format string and arguments.

Syntax:

public static String format(String format, Object... args)
  • format: A format string that can contain fixed text and one or more format specifiers.
  • args: A variable number of arguments (a varargs Object...) that will be inserted into the format string.

The Format Specifier

The core of String.format() is the format specifier. It tells the method how to format a specific argument. The general syntax is:

Java中string.format如何使用?-图2
(图片来源网络,侵删)

%[argument_index$][flags][width][.precision]conversion

Let's break down each part:

Component Description Example
The start of a format specifier. %d
[argument_index$] (Optional) The index of the argument to format, followed by a . The first argument is 1$, the second is 2$, etc. If omitted, arguments are used in order. %1$d (refers to the first argument)
`[flags]` (Optional) A set of characters that modify the output. , `,0,(`
[width] (Optional) The minimum number of characters to be written to the output. %5d
.[precision] (Optional) For floating-point numbers, the number of digits after the decimal point. For s and S, the maximum number of characters to be printed. %.2f
conversion (Required) A character that specifies the type of data to be formatted. d, f, s, c

Common Conversions

This is the most important part. The conversion character determines how the argument is interpreted and displayed.

Conversion Type Description Example
d or i int, byte, short, long Formats the argument as a decimal integer. String.format("Age: %d", 30) -> "Age: 30"
f float, double Formats the argument as a decimal floating-point number. String.format("Pi: %.2f", 3.14159) -> "Pi: 3.14"
s or S Object, String Formats the argument using its toString() method. S converts to uppercase. String.format("Name: %s", "Alice") -> "Name: Alice"
c or C char Formats the argument as a character. C converts to uppercase. String.format("Initial: %c", 'a') -> "Initial: a"
b or B Object Formats the argument as true or false. B converts to uppercase. String.format("Active: %b", true) -> "Active: true"
t or T long, Calendar, Date Date/Time Formatting. t is lowercase, T is uppercase. String.format("Time: %tH:%tM", now, now) -> "Time: 14:30"
n N/A Platform-independent newline character. String.format("Line1%nLine2") -> "Line1\nLine2"

Examples

Basic Formatting

int age = 30;
String name = "Bob";
double salary = 75000.555;
String formattedString = String.format("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
System.out.println(formattedString);
// Output: Name: Bob, Age: 30, Salary: 75000.56

Using Argument Index

This is useful when you want to reuse an argument or reorder them.

Java中string.format如何使用?-图3
(图片来源网络,侵删)
int x = 10;
int y = 20;
// Reuse the first argument (x)
String result = String.format("x=%1$d, y=%2$d, sum=%1$d + %2$d = %3$d", x, y, x + y);
System.out.println(result);
// Output: x=10, y=20, sum=10 + 20 = 30

Using Flags

Flags are added between the and the width or conversion.

Flag Description Example
Includes a sign ( or ) for the number. String.format("%+d", -123) -> "-123"
String.format("%+d", 123) -> "+123"
` ` (space) Puts a space before a positive number. String.format("% d", 123) -> " 123"
0 Pads with zeros instead of spaces. String.format("%05d", 99) -> "00099"
Adds locale-specific grouping separators (e.g., comma for thousands). String.format("%,d", 1234567) -> "1,234,567"
Left-justifies the output (default is right-justified). String.format("%-10s|", "Left") -> "Left |"
int number = -12345;
double pi = 3.14159;
System.out.println(String.format("With comma: %,d", number));
// Output: With comma: -12,345
System.out.println(String.format("With sign: %+d, With zero: %010d", number, number));
// Output: With sign: -12345, With zero: -000012345

Date and Time Formatting (t or T)

To format dates, you typically use java.time classes like LocalDate and LocalTime. The format specifier starts with t or T.

Conversion Description Example (now is a LocalTime)
H Hour of the day (00-23) String.format("%tH", now) -> "14"
I Hour (12-hour clock) (01-12) String.format("%tI", now) -> "02"
M Minute in hour (00-59) String.format("%tM", now) -> "30"
S Second in minute (00-60) String.format("%tS", now) -> "05"
p Locale-specific AM/PM marker String.format("%tp", now) -> "PM"
Y Year (e.g., 2025) String.format("%tY", now) -> "2025"
B Full month name (e.g., January) String.format("%tB", now) -> "January"
d Day of the month (01-31) String.format("%td", now) -> "24"
F ISO-8601 full date (YYYY-MM-DD) String.format("%tF", now) -> "2025-01-24"
R 24-hour time (HH:MM) String.format("%tR", now) -> "14:30"
r 12-hour time (HH:MM:SS AM/PM) String.format("%tr", now) -> "02:30:05 PM"
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Date: " + String.format("%tY-%tm-%td", today, today, today));
// A simpler way for the same date: System.out.println("Date: " + String.format("%tF", today));
// Output: Date: 2025-01-24
System.out.println("Time: " + String.format("%tH:%tM:%tS", now, now, now));
// A simpler way for the same time: System.out.println("Time: " + String.format("%tT", now));
// Output: Time: 14:30:05
System.out.println("Full: " + String.format("%ta, %td %tb, %tY", dateTime, dateTime, dateTime, dateTime));
// Output: Full: Wed, 24 Jan, 2025

System.out.printf() vs. String.format()

You will often see System.out.printf(). It's very similar but serves a slightly different purpose.

Method Description Return Value Example
String.format() Formats a string and returns it. The original string is not modified. String String s = String.format("Hello, %s!", "World");
System.out.printf() Formats a string and prints it directly to the standard output stream (usually the console). PrintStream (itself, for chaining) System.out.printf("Hello, %s!", "World");

Think of printf as a convenient shortcut for System.out.print(String.format(...)).


Modern Alternative: Text Blocks (Java 15+)

For simple, multi-line strings where you don't need complex variable insertion, Java's text blocks are a cleaner alternative.

// Before text blocks
String html = "<html>\n" +
              "  <body>\n" +
              "    <h1>" + title + "</h1>\n" +
              "  </body>\n" +
              "</html>";
// With text blocks (Java 15+)
String htmlBlock = """
    <html>
      <body>
        <h1>%s</h1>
      </body>
    </html>
    """.formatted(title); // Note: .formatted() is the method version of String.format()

Summary

Feature String.format() System.out.printf()
Purpose Create a formatted String object. Print a formatted string directly to the console.
Return Value The formatted String. The PrintStream object (for method chaining).
Best For When you need to store, pass, or manipulate the formatted string. Quick, direct output to the console.

For most use cases involving dynamic string creation, String.format() is the go-to method in Java.

分享:
扫描分享到社交APP
上一篇
下一篇