formatted()
方法和format()
静态方法,可以传入其他参数,替换占位符,然后生成新的字符串:
public class Main {
public static void main(String[] args) {
String s = "Hi %s, your score is %d!";
System.out.println(s.formatted("Alice", 80));
System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5));
}
}
运行结果:
Hi Alice, your score is 80!
Hi Bob, your score is 59.50!
有几个占位符,后面就传入几个参数。参数类型要和占位符一致。我们经常用这个方法来格式化信息。常用的占位符有:
%s:显示字符串;
%d:显示整数;
%x:显示十六进制整数;
%f:显示浮点数。
©查看原文