使用 % 在 Java 中格式化字符串

javaobject oriented programmingprogramming更新于 2025/7/8 16:12:17

以下是使用 % 在 Java 中实现格式化字符串的代码 −

示例

public class Demo {
   public static void main(String args[]){
      String my_str = " sample.";
      String concat_Str = String.format("This is a" + "%s", my_str);
      String format_str_1 = String.format("The value is %.4f", 78.92367);
      System.out.println(concat_Str);
      System.out.println(format_str_1);
   }
}

输出

This is a sample.
The value is 78.9237

名为 Demo 的类包含主要函数。这里定义了一个字符串值,用于通过将其连接到另一个变量来格式化字符串。同样,浮点数也使用‘%’运算符进行格式化。这两个值都打印在控制台上。


相关文章


有用资源