小番茄程序员 ©免责声明

文章标签 string String.format 文章分类 后端技术 阅读数 49

@免责声明:本文转载来自互联网,不代表本网站的观点和立场。 如果你觉得好,欢迎分享此网址给你的朋友。

Java中,String.format() 方法用于格式化字符串。它通过指定格式字符串和参数来生成一个格式化的新字符串。下面是 String.format() 方法的详细用法:

String formattedString = String.format(format, arg1, arg2, ...);

其中,format 是格式字符串,arg1, arg2, ... 是要格式化的参数。

格式字符串中可以包含转换符和格式修饰符,用于指定参数的输出格式。常用的转换符有:

  • %s:字符串类型。
  • %d:整数类型。
  • %f:浮点数类型。
  • %c:字符类型。
  • %b:布尔类型。
  • %t:日期/时间类型。

以下是一些示例:

  1. 字符串类型的格式化:

    String name = "Alice";
    int age = 25;
    String formattedString = String.format("My name is %s and I'm %d years old.", name, age);
    System.out.println(formattedString); // 输出 "My name is Alice and I'm 25 years old."
    

    在这个例子中, %s%d 分别代表字符串类型和整数类型的参数,它们会被相应的值替换。

  2. 浮点数类型的格式化:

    double pi = 3.14159;
    String formattedString = String.format("The value of pi is approximately %.2f.", pi);
    System.out.println(formattedString); // 输出 "The value of pi is approximately 3.14."
    

    在这个例子中,%.2f 表示保留两位小数的浮点数。

  3. 日期/时间类型的格式化:

    import java.util.Date;
    Date now = new Date();
    String formattedString = String.format("Current time is %tT on %tF.", now, now);
    System.out.println(formattedString); // 输出 "Current time is 09:30:45 on 2023-08-08."
    

    在这个例子中,%tT 表示输出完整的时间,%tF 表示输出完整的日期。

除了转换符,还可以使用格式修饰符来进一步指定输出格式。例如,使用 %20s 可以将字符串右对齐并占据 20 个字符的宽度。

本文地址:https://www.meishiadd.com/java/167.html

相关文章

友情链接

Copyright © 2021-2023 MEISHIADD.COM 版权所有 京ICP备14024137号