📜  Java字符串format()(1)

📅  最后修改于: 2023-12-03 15:32:03.082000             🧑  作者: Mango

Java字符串format()

在Java中,字符串格式化是一个常见的操作。字符串格式化是指将变量的值插入到字符串字面量中来生成新的字符串。

Java提供了许多方法来格式化字符串,其中最常用的是String.format()方法。

String.format()方法可以使用类似于C语言中的printf()函数的占位符来指示字符串中应该插入的变量。下面是一个简单的例子:

String name = "Alice";
int age = 25;
String message = String.format("%s is %d years old.", name, age);
System.out.println(message);

这将输出:

Alice is 25 years old.

在上面的例子中,%s%d是占位符。%s表示要插入一个字符串,%d表示要插入一个整数。在String.format()方法中,每个占位符都对应一个变量。第一个占位符%s对应name,第二个占位符%d对应age。在生成消息字符串时,nameage的值被插入到相应的占位符中。

以下是一些常用的占位符:

| 占位符 | 描述 | |------|------------------------------------------| | %s | 字符串 | | %d | 十进制整数 | | %f | 浮点数 | | %t | 日期/时间 | | %c | 字符 | | %b | 布尔值 | | %% | 百分号 | | %n | 换行符 | | %o | 八进制数 | | %x | 十六进制数 | | %h | 哈希码 |

以下是一些例子:

String name = "Bob";
int age = 30;
double salary = 12345.67;
String message = String.format("%s is %d years old and earns $%.2f per month.", name, age, salary);
System.out.println(message);

String date = String.format("Today is %tA, %<tB %<te, %<tY.", new Date());
System.out.println(date);

String hex = String.format("The hexadecimal representation of %d is %<x.", 42);
System.out.println(hex);

这将输出:

Bob is 30 years old and earns $12345.67 per month.
Today is Tuesday, April 20, 2021.
The hexadecimal representation of 42 is 2a.

在第一个例子中,%.2f表示要插入一个浮点数,并格式化为两位小数。在第二个例子中,%tA表示要插入当前日期的完整星期几名称(例如“Tuesday”),%tB表示要插入当前日期的完整月份名称(例如“April”),%<te表示要插入当前日期的日期(不带前导零),%<tY表示要插入当前年份。在第三个例子中,%<x表示要插入与先前插入的整数相同的十六进制表示。

String.format()方法还支持其他功能,如在占位符中指定最小宽度、精度、左对齐等。您可以在Java文档中查找更多的详细信息。

总的来说,String.format()方法是一种非常灵活和方便的方法来格式化字符串,并插入变量的值。它值得您在编写Java代码时进行学习和掌握。