String.format 用法详解

String.format 是 Java 中用于格式化字符串的一个方法,它允许你通过占位符来创建一个格式化的字符串。使用 String.format 可以将各种类型的数据(如整数、小数、字符串等)以指定的格式组合成一个字符串。

下面是 String.format 方法的基本用法详解:

1. 基本语法

String formattedString = String.format(String format, Object... args);
  • format: 一个包含格式说明符的字符串。
  • args: 对应格式说明符的参数,可以是多个。

2. 常用的格式说明符

  • %s - 字符串
  • %d - 十进制整数
  • %f - 浮点数
  • %x - 十六进制整数
  • %o - 八进制整数
  • %c - 单个字符
  • %% - 字符 % 本身

3. 示例

3.1 字符串格式化
String name = "Alice";
String message = String.format("Hello, %s!", name);
System.out.println(message);  // 输出: Hello, Alice!
3.2 整数格式化
int value = 42;
String formattedValue = String.format("Value: %d", value);
System.out.println(formattedValue);  // 输出: Value: 42
3.3 浮点数格式化
double pi = 3.14159;
String formattedPi = String.format("Pi: %.2f", pi);
System.out.println(formattedPi);  // 输出: Pi: 3.14
  • %.2f 中的 .2 表示保留两位小数。
3.4 填充与对齐
  • %n - 换行符
  • %5d - 右对齐,宽度为5个字符
  • %-5d - 左对齐,宽度为5个字符
  • %05d - 右对齐,宽度为5个字符,用0填充
int num = 7;
String paddedNumber = String.format("Number: %05d", num);
System.out.println(paddedNumber);  // 输出: Number: 00007
3.5 多个参数
String firstName = "John";
String lastName = "Doe";
int age = 30;
String formattedString = String.format("Name: %s %s, Age: %d", firstName, lastName, age);
System.out.println(formattedString);  // 输出: Name: John Doe, Age: 30

4. 进阶用法

4.1 位置参数

使用 $ 来指定参数的位置:

String formattedString = String.format("%1$s %2$s %1$s", "Hello", "World");
System.out.println(formattedString);  // 输出: Hello World Hello
  • %1$s%2$s 分别表示第一个和第二个参数。
4.2 本地化格式化

String.format 支持本地化,通过 Locale 参数可以将格式化字符串根据指定的地区进行调整:

Locale locale = new Locale("fr", "FR");
String formattedNumber = String.format(locale, "%,d", 1000000);
System.out.println(formattedNumber);  // 输出: 1 000 000 (法式千位分隔符)

总结

String.format 是一个强大的工具,适用于生成格式化的字符串,可以处理各种数据类型并根据需要进行精确控制。通过了解和掌握其使用方法,可以编写出更为清晰和结构化的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值