声明
- 原文地址:https://blog.csdn.net/qq_27390023/article/details/139621816
前言
String.format
是 Java 中的一个静态方法,用于创建格式化的字符串。它类似于 C 语言中的 printf
函数,允许使用格式说明符来格式化字符串。String.format
方法非常灵活,可以处理多种数据类型和格式化需求。
基本语法
public static String format(String format, Object… args)
- format:格式字符串,其中包含文本和格式说明符。
- args:格式说明符对应的参数列表。
格式说明符
格式说明符以 %
开头,后跟一个字符,表示一种特定的格式类型。常用的格式说明符包括:
- %d:整数
- %f:浮点数
- %s:字符串
- %c:字符
- %b:布尔值
- %%:百分号
格式化说明符的详细解释
1. 格式化整数
- %d:格式化为十进制整数。
- %x:格式化为十六进制整数。
- %o:格式化为八进制整数。
2. 格式化浮点数
- %f:格式化为十进制浮点数。
- %e:格式化为科学计数法。
- %g:根据值的大小,自动选择
%f
或%e
。
3. 格式化字符串
- %s:格式化为字符串。
4. 格式化字符
- %c:格式化为字符
5. 格式化布尔值
- %b:格式化为布尔值。
示例代码
public class StringFormatExample {
public static void main(String[] args) {
// 格式化整数
String intFormatted = String.format("This is an integer: %d", 42);
System.out.println(intFormatted); // 输出:This is an integer: 42
// 格式化浮点数
String floatFormatted = String.format("This is a float: %.2f", 3.14159);
System.out.println(floatFormatted); // 输出:This is a float: 3.14
// 格式化字符串
String stringFormatted = String.format("This is a string: %s", "hello");
System.out.println(stringFormatted); // 输出:This is a string: hello
// 格式化字符
String charFormatted = String.format("This is a character: %c", 'A');
System.out.println(charFormatted); // 输出:This is a character: A
// 格式化布尔值
String booleanFormatted = String.format("This is a boolean: %b", true);
System.out.println(booleanFormatted); // 输出:This is a boolean: true
// 百分号
String percentFormatted = String.format("This is a percent sign: %%");
System.out.println(percentFormatted); // 输出:This is a percent sign: %
}
}
高级格式化示例
public class StringFormatExample {
public static void main(String[] args) {
// 格式化整数,带符号和宽度
String intFormatted = String.format("This is an integer with sign: %+d", 42);
System.out.println(intFormatted); // 输出:This is an integer with sign: +42
// 格式化整数,带填充
String intPadded = String.format("This is a padded integer: %05d", 42);
System.out.println(intPadded); // 输出:This is a padded integer: 00042
// 格式化浮点数,带宽度和对齐
String floatAligned = String.format("This is a left-aligned float: %-10.2f", 3.14159);
System.out.println(floatAligned); // 输出:This is a left-aligned float: 3.14
// 格式化字符串,带宽度和对齐
String stringAligned = String.format("This is a right-aligned string: %10s", "hello");
System.out.println(stringAligned); // 输出:This is a right-aligned string: hello
// 格式化多个参数
String multiFormatted = String.format("Name: %s, Age: %d, GPA: %.2f", "Alice", 30, 3.75);
System.out.println(multiFormatted); // 输出:Name: Alice, Age: 30, GPA: 3.75
}
}
总结
String.format
方法在 Java 中非常有用,可以通过格式说明符来灵活地创建格式化的字符串。它适用于多种数据类型和格式化需求,能够显著提高代码的可读性和可维护性。- 在日常编程中,熟练使用
String.format
方法将使得格式化输出更加简洁和高效。