// 使用 String.format 方法格式化字符串
public class Main {
public static void main(String[] args) {
// 示例 1: 简单的字符串格式化
String name = "Alice";
int age = 30;
String formattedString = String.format("Name: %s, Age: %d", name, age);
System.out.println(formattedString); // 输出: Name: Alice, Age: 30
// 示例 2: 格式化浮点数,保留两位小数
double price = 123.456;
String priceFormatted = String.format("Price: %.2f", price);
System.out.println(priceFormatted); // 输出: Price: 123.46
// 示例 3: 使用占位符索引
String result = String.format("The value at index 1 is %2$s and at index 0 is %1$d", 10, "hello");
System.out.println(result); // 输出: The value at index 1 is hello and at index 0 is 10
}
}
String.format
是 Java 中用于格式化字符串的方法,类似于 C 语言中的 printf
。%s
表示字符串占位符,%d
表示整数占位符,%.2f
表示浮点数并保留两位小数。%1$d
表示第一个参数是整数,%2$s
表示第二个参数是字符串。上一篇:java base64
下一篇:java 获取当前时间
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站