杰瑞科技汇

Java format字符串如何正确使用?

Of course! In Java, formatting strings is a common task. The primary and most powerful way to do this is using String.format(). It's similar to the printf function in C/C++ and offers a lot of flexibility.

Java format字符串如何正确使用?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering the main methods and their use cases.


The Modern Way: String.format()

This is the recommended approach for most formatting tasks. It returns a new, formatted string without modifying the original.

Syntax

String formattedString = String.format(formatString, arg1, arg2, ...);

The magic happens in the formatString, which contains special format specifiers.

Java format字符串如何正确使用?-图2
(图片来源网络,侵删)

Format Specifier Structure

A format specifier starts with a and ends with a letter. The general structure is:

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

Let's break that down:

Component Description Example
Starts the specifier. %d
flags (Optional) Controls formatting. (left-align), (show sign), 0 (zero-pad)
width (Optional) Minimum number of characters to output. 10 in %-10d
.precision (Optional) For floating-point numbers, it's the number of decimal places. .2f for 2 decimal places.
conversion (Required) The type of data to format. d (decimal), f (float), s (string)

Common Conversion Types

Conversion Type Example
b boolean String.format("%b", true) -> "true"
c char String.format("%c", 'A') -> "A"
d decimal integer String.format("%d", 123) -> "123"
f floating-point String.format("%.2f", 3.14159) -> "3.14"
e scientific notation String.format("%e", 1000.0) -> "1.000000e+03"
s string String.format("%s", "Hello") -> "Hello"
x hexadecimal integer String.format("%x", 255) -> "ff"
h hashcode String.format("%h", "test") -> "4e71a7e6"

Flags

Flag Description Example
Left-justify the output in the given width. String.format("%-10s", "left") -> "left "
Include a sign ( or ) for numbers. String.format("%+d", 10) -> "+10"
0 Pad with leading zeros. String.format("%05d", 42) -> "00042"
Use locale-specific grouping separators (e.g., comma for thousands). String.format("%,d", 1000000) -> "1,000,000"
Alternate form (e.g., add a leading 0x for hex). String.format("#x", 255) -> "0xff"

Practical Examples

Let's put it all together.

Java format字符串如何正确使用?-图3
(图片来源网络,侵删)

Basic Formatting

int age = 30;
String name = "Alice";
double salary = 75000.5555;
// Basic formatting
String s1 = String.format("Name: %s, Age: %d", name, age);
System.out.println(s1); // Output: Name: Alice, Age: 30
// Formatting with width and precision
String s2 = String.format("Salary: $%,.2f", salary);
System.out.println(s2); // Output: Salary: $75,000.56

Using Flags and Width

int number = 42;
String text = "Java";
// Left-align in a 10-character space
String s3 = String.format("Number: |%-10d|", number);
System.out.println(s3); // Output: Number: |42        |
// Right-align in a 10-character space (default)
String s4 = String.format("Number: |%10d|", number);
System.out.println(s4); // Output: Number: |        42|
// Zero-pad to a width of 5
String s5 = String.format("Padded: |%05d|", number);
System.out.println(s5); // Output: Padded: |00042|
// Left-align text in a 15-character space
String s6 = String.format("Text: |%-15s|", text);
System.out.println(s6); // Output: Text: |Java           |

Formatting Dates and Times

The t or T conversion is used for dates and times. You append a specific letter after it.

Code Meaning Example
Y 4-digit year 2025
y 2-digit year 23
m Month (01-12) 11
d Day of month (01-31) 25
B Full month name November
b Abbreviated month name Nov
A Full weekday name Saturday
a Abbreviated weekday name Sat
H Hour (00-23) 14
I Hour (01-12) 02
M Minute (00-59) 30
S Second (00-60) 05
p AM/PM marker PM
import java.util.Date;
Date now = new Date();
// Full date and time
String s7 = String.format("Full date: %tc", now);
System.out.println(s7); // e.g., Full date: Sat Nov 25 14:30:05 CST 2025
// Custom format
String s8 = String.format("Year-Month-Day: %tF", now);
System.out.println(s8); // e.g., Year-Month-Day: 2025-11-25
// Time with AM/PM
String s9 = String.format("Time: %tr", now);
System.out.println(s9); // e.g., Time: 02:30:05 PM

Other Ways to Format Strings

While String.format() is the most versatile, there are other methods for simpler cases.

System.out.printf()

This method prints the formatted string directly to the console (standard output). It's identical to String.format() but doesn't return a new string.

int apples = 10;
int oranges = 5;
// Prints directly to the console
System.out.printf("I have %d apples and %d oranges.\n", apples, oranges);

Formatter Class

This is the low-level engine that String.format() and System.out.printf() use. It's useful for writing formatted output to different destinations, like a file or a network stream.

import java.util.Formatter;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("Hello, %s! You have %d new messages.", "Bob", 3);
// The formatted string is in the StringBuilder
System.out.println(sb.toString()); // Output: Hello, Bob! You have 3 new messages.
formatter.close();

The "Old" Way: Concatenation

Before String.format() was introduced, the primary way to combine strings was with the operator.

String name = "Charlie";
int score = 95;
String oldWay = "Player: " + name + ", Score: " + score;
System.out.println(oldWay); // Output: Player: Charlie, Score: 95

Why is String.format() better?

  • Readability: String.format("Name: %s, Age: %d", name, age) is much cleaner and less error-prone than "Name: " + name + ", Age: " + age.
  • Performance: For multiple concatenations in a loop, String.format() or using StringBuilder is significantly more efficient. The operator creates a new String object in memory for each concatenation, which can be very slow.
  • Localization: String.format() makes it easy to format numbers and dates according to different locales (e.g., using as a thousands separator in the US vs. in some European countries).

Summary: Which one should I use?

Method Best For Pros Cons
String.format() Most cases. Creating formatted strings. Highly readable, flexible, powerful, good performance. Slightly more verbose than for very simple cases.
System.out.printf() Quick debugging. Printing directly to the console. Convenient for printing. Only prints, doesn't create a string.
Concatenation Very simple cases. Combining 2-3 strings. Very simple syntax. Inefficient for loops, poor readability for complex strings.
StringBuilder High-performance loops. Building strings in a loop. Most memory-efficient for repeated appends. More verbose for simple one-off formatting.
分享:
扫描分享到社交APP
上一篇
下一篇