首页 文章资讯内容详情

Java中使用%(百分号)格式化字符串

2026-06-03 1 花语

以下是使用%在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的类包含主函数。这里定义了一个字符串值,通过将其连接到另一个变量来格式化该字符串。类似地,也使用%运算符对浮点数进行格式化。这两个值都打印在控制台上。