如何在 Java 中格式化字符串
字符串格式化是将 字符串 的输出修改为特定格式的过程,例如变量的占位符、文本对齐和格式化数值。以下是 Java 中使用 format() 方法的方法,该方法允许更准确地在输出中呈现值。
使用字符串 format() 方法
字符串 format() 方法 方法允许使用不同的格式说明符格式化字符串、整数和十进制值。此方法根据指定的语言环境、格式化程序和参数返回格式化的字符串,如果没有给出语言环境,则使用默认值。 String.format() 是 Java String 类的静态方法。
语法
以下是 Java String format() 方法的语法 −
public static String format(Locale l, String format, Object... args) //第一个语法 public static String format(String format, Object... args) //第二个语法
示例 1
以下示例使用 format() 方法中的特定语言环境、格式和参数返回格式化的字符串值 −
import java.util.*; public class StringFormat{ public static void main(String[] args){ double e = Math.E; System.out.format("%f%n", e); System.out.format(Locale.GERMANY, "%-10.4f%n%n", e); } }
输出
2.718282 2,7183
示例 2
以下是格式字符串的另一个示例 -
public class HelloWorld { public static void main(String []args) { String name = "Hello World"; String s1 = String.format("name %s", name); String s2 = String.format("value %f",32.33434); String s3 = String.format("value %32.12f",32.33434); System.out.print(s1); System.out.print(" "); System.out.print(s2); System.out.print(" "); System.out.print(s3); System.out.print(" "); } }
输出
name Hello World value 32.334340 value 32.334340000000
java_strings.html