1. 使用 String.format()
进行格式化
String.format()
是 Java 中最常用的字符串格式化方法之一,它采用类似于 C 语言 printf
的格式化方式,支持各种数据类型的格式化。
1.1 基本语法
String formattedString = String.format(String format, Object... args);
format
:格式化字符串,其中包含格式说明符(例如%d
、%s
、%f
等)。args
:一个或多个要格式化的参数。
1.2 常用的格式说明符
%d
:整数(十进制)%x
:整数(十六进制)%f
:浮点数%s
:字符串%c
:字符%b
:布尔值%t
:日期/时间
1.3 示例
public class FormatExample {
public static void main(String[] args) {
int number = 42;
String name = "John";
double price = 19.99;
String formatted = String.format("Number: %d, Name: %s, Price: %.2f", number, name, price);
System.out.println(formatted);
}
}
输出结果:
Number: 42, Name: John, Price: 19.99
1.4 其他格式化选项
- 宽度和精度:
%5d
表示宽度为 5 的整数,%.2f
表示精度为 2 的浮点数。 - 左对齐:
%-10s
表示左对齐的字符串,宽度为 10。
2. 使用 System.out.printf()
进行格式化输出
System.out.printf()
方法类似于 String.format()
,但它直接输出格式化后的字符串到控制台。
2.1 基本语法
System.out.printf(String format, Object... args);
2.2 示例
public class PrintfExample {
public static void main(String[] args) {
int number = 7;
String language = "Java";
float percentage = 85.567f;
System.out.printf("Language: %s, Score: %d, Percentage: %.2f%%", language, number, percentage);
}
}
输出结果:
Language: Java, Score: 7, Percentage: 85.57%
3. 使用 MessageFormat
进行国际化和复杂格式化
MessageFormat
是 Java 提供的一个强大的格式化类,主要用于国际化(i18n)场景下的字符串格式化。它允许使用带占位符的字符串模板,并支持复杂的格式化规则。
3.1 基本语法
String formattedString = MessageFormat.format(String pattern, Object... arguments);
pattern
:包含占位符的字符串模板,如"{0}, you have {1} new messages"
.arguments
:一个或多个要格式化的参数。
3.2 示例
import java.text.MessageFormat;
public class MessageFormatExample {
public static void main(String[] args) {
String pattern = "{0}, you have {1} new messages";
String user = "Alice";
int messageCount = 5;
String formatted = MessageFormat.format(pattern, user, messageCount);
System.out.println(formatted);
}
}
输出结果:
Alice, you have 5 new messages
3.3 日期和数字格式化
MessageFormat
还支持使用格式化模式来处理日期、时间和数字。
import java.text.MessageFormat;
import java.util.Date;
public class MessageFormatExample2 {
public static void main(String[] args) {
String pattern = "At {1,time} on {1,date}, {0} paid {2,number,currency}.";
Object[] arguments = {"Alice", new Date(), 1234.56};
String formatted = MessageFormat.format(pattern, arguments);
System.out.println(formatted);
}
}
输出结果:
At 3:15:48 PM on Mar 1, 2024, Alice paid $1,234.56.
4. 使用 StringBuilder
和 StringBuffer
进行字符串拼接
虽然 StringBuilder
和 StringBuffer
主要用于高效地拼接字符串,但它们也可以用于简单的字符串格式化。StringBuilder
是线程不安全的,而 StringBuffer
是线程安全的。
4.1 基本用法
StringBuilder builder = new StringBuilder();
builder.append("Hello, ");
builder.append("World!");
String result = builder.toString();
4.2 示例
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("Name: ").append("Alice").append(", ");
builder.append("Age: ").append(30);
String result = builder.toString();
System.out.println(result);
}
}
输出结果:
Name: Alice, Age: 30
4.3 使用 appendFormat
如果你在 Java 8 之前使用 Apache Commons Lang 库,也可以使用 StrBuilder
类,它提供了 appendFormat
方法,类似于 String.format()
。
import org.apache.commons.lang3.text.StrBuilder;
public class StrBuilderExample {
public static void main(String[] args) {
StrBuilder builder = new StrBuilder();
builder.appendFormat("Name: %s, Age: %d", "Alice", 30);
String result = builder.toString();
System.out.println(result);
}
}
输出结果:
Name: Alice, Age: 30
5. 使用 String.join()
进行字符串拼接
String.join()
是 Java 8 中引入的一种用于拼接字符串的新方法,特别适合处理集合或数组中的字符串拼接。
5.1 基本语法
String result = String.join(CharSequence delimiter, CharSequence... elements);
5.2 示例
public class StringJoinExample {
public static void main(String[] args) {
String[] words = {"Java", "Python", "C++"};
String result = String.join(", ", words);
System.out.println(result);
}
}
输出结果:
Java, Python, C++
6. 使用 String.format()
进行本地化
String.format()
还支持使用 Locale
参数,方便进行本地化格式化,特别是在处理货币、数字和日期时非常有用。
6.1 示例
import java.util.Locale;
public class LocaleFormatExample {
public static void main(String[] args) {
double price = 1234.56;
String formatted = String.format(Locale.FRANCE, "Price: %.2f", price);
System.out.println(formatted);
}
}
输出结果:
Price: 1234,56
在这个例子中,价格格式使用了法国的区域设置,其中小数点使用逗号而不是句点。
7. 总结
在 Java 中,字符串格式化有多种方式可供选择,适用于不同的场景:
String.format()
:最通用、灵活的方法,适合各种数据类型的格式化。System.out.printf()
:用于格式化输出到控制台,语法与String.format()
类似。MessageFormat
:适用于国际化场景,可以处理复杂的格式化需求。StringBuilder
和StringBuffer
:用于高效地拼接字符串,适合在循环中构建字符串。String.join()
:用于将数组或集合中的字符串拼接成一个字符串,常用于列表或数组输出。