杰瑞科技汇

Java String Format如何实现格式化?

Of course! In Java, there are several ways to format strings, ranging from simple concatenation to powerful, flexible formatting. Here’s a comprehensive guide, starting with the modern recommended approach.

Java String Format如何实现格式化?-图1
(图片来源网络,侵删)

The Modern Way: String.formatted() (Java 15+)

This is the cleanest and most modern approach. It's an instance method on the String class that takes a format string and a variable number of arguments.

How it works:

  • You start with a format string containing placeholders.
  • Placeholders are denoted by followed by a format specifier (e.g., %s for string, %d for integer).
  • You call the .formatted() method on your format string, passing the variables that should replace the placeholders.

Format Specifier Syntax: %[argument_index$][flags][width][.precision]conversion

  • conversion: The most important part. It specifies the type of the argument.

    Java String Format如何实现格式化?-图2
    (图片来源网络,侵删)
    • s: String
    • d: Decimal integer (base 10)
    • f: Floating-point number
    • c: Character
    • b: Boolean ("true" or "false")
    • t: Date/Time (requires a Date or Calendar object)
    • Literal percent sign
  • width: Minimum number of characters to be written in the output. If the value is shorter, it's padded with spaces. If longer, it's not truncated.

  • .precision: For floating-point numbers (f), it's the number of digits after the decimal point. For general types (s), it's the maximum number of characters to be printed.

Example:

String name = "Alice";
int age = 30;
double salary = 123456.789;
// Using String.formatted()
String message = "Name: %s, Age: %d, Salary: %.2f".formatted(name, age, salary);
System.out.println(message);
// Output: Name: Alice, Age: 30, Salary: 123456.79

The Classic Way: String.format() (Java 5+)

This is the most common and widely used method. It's a static method in the String class. The syntax and format specifiers are identical to String.formatted().

Java String Format如何实现格式化?-图3
(图片来源网络,侵删)

The only difference is that String.format() is a static method that takes the format string and arguments as separate parameters, whereas String.formatted() is an instance method called on the format string itself.

How it works: String.format(formatString, arg1, arg2, ...)

Example:

String name = "Bob";
int id = 101;
boolean isActive = true;
String report = String.format(
    "User Report: [ID: %d, Name: %s, Active: %b]", 
    id, 
    name, 
    isActive
);
System.out.println(report);
// Output: User Report: [ID: 101, Name: Bob, Active: true]

The Powerful Way: System.out.printf() (Java 5+)

This method is very similar to String.format(), but instead of returning a formatted string, it prints the formatted string directly to the standard output stream (System.out).

This is extremely useful for console output and debugging.

How it works: System.out.printf(formatString, arg1, arg2, ...);

Example:

String product = "Laptop";
int quantity = 2;
double price = 1200.50;
System.out.printf("Order: %d x %s @ $%.2f each%n", quantity, product, price);
// Note: %n is the platform-independent newline character. It's preferred over \n.
// Output:
// Order: 2 x Laptop @ $1200.50 each

The Old Way: String Concatenation ( operator)

Before Java 5, this was the primary way to build strings. It's simple but can be inefficient and hard to read for complex messages.

How it works: Use the operator to join strings and variables.

Example:

String city = "New York";
int population = 8400000;
String info = "The population of " + city + " is " + population + ".";
System.out.println(info);
// Output: The population of New York is 8400000.

Why avoid it for complex formatting?

  • Readability: It gets messy with many variables.
  • Performance: Using in a loop creates many intermediate String objects, which is inefficient. Use StringBuilder for that.

The Flexible Way: Formatter Class (Java 5+)

The java.util.Formatter class is the engine behind String.format() and System.out.printf(). You can use it directly for more advanced scenarios, like writing to a file or another output stream.

Example:

import java.util.Formatter;
StringBuffer sb = new StringBuffer();
Formatter formatter = new Formatter(sb);
// The first argument to format() is the destination (our StringBuffer)
formatter.format("Hello, %s! You have %d new messages.", "Charlie", 5);
// The formatted result is now in the StringBuffer
System.out.println(sb.toString());
// Output: Hello, Charlie! You have 5 new messages.
formatter.close(); // Good practice to close the formatter

Comparison and When to Use What

Method When to Use Key Advantage
String.format() Default choice. When you need a formatted string to store, pass to another method, or return. Clean, widely compatible, and separates formatting from output.
String.formatted() Modern alternative. Same as String.format(), but can feel more natural as it's an instance method. More fluent, object-oriented syntax.
System.out.printf() Console output. When you just want to print directly to the console. Convenient for quick debugging and logging.
Concatenation Simple cases. For very simple, one-off string building. Simplicity for trivial cases.
Formatter Advanced I/O. When you need to format output to a file, a network socket, or another Appendable object. Maximum flexibility and power.

Complete Example with Different Specifiers

int integer = 12345;
double floating = 98.7654;
String text = "formatting";
char character = 'Z';
boolean bool = true;
// String.format() example
String formatted = String.format(
    "Integer: %d | Float: %.2f | String: %s | Char: %c | Bool: %b | Percent: %%",
    integer, floating, text, character, bool
);
System.out.println("--- String.format() ---");
System.out.println(formatted);
// System.out.printf() example
System.out.println("\n--- System.out.printf() ---");
System.out.printf("Padded Integer: %10d | Left-aligned: %-10d | With Commas: %,d%n", integer, integer, 1000000);
// Using width and precision
System.out.printf("Width 10: %10.2f | Width 5: %5.2f%n", floating, floating);

Output of the complete example:

--- String.format() ---
Integer: 12345 | Float: 98.77 | String: formatting | Char: Z | Bool: true | Percent: %
--- System.out.printf() ---
Padded Integer:      12345 | Left-aligned: 12345     | With Commas: 1,000,000
Width 10:     98.77 | Width 5: 98.77

Key Takeaways

  1. For most new code, use String.format() or String.formatted(). They are the standard, readable, and powerful way to create formatted strings.
  2. Use System.out.printf() for direct console printing. It's a convenient shortcut.
  3. Learn the format specifiers (%s, %d, %f, etc.). They are the core of the formatting system.
  4. Use %n for newlines. It ensures correct line endings across all operating systems (Windows, Linux, macOS).
  5. Avoid string concatenation () in loops for performance reasons; prefer StringBuilder in those cases.
分享:
扫描分享到社交APP
上一篇
下一篇