Java 相当于 .NET's String.Format

2022-08-31 15:44:55

是否存在等效项。NET's in Java?String.Format


答案 1

对此的10美分答案是:

C#的


String.Format("{0} -- {1} -- {2}", ob1, ob2, ob3)

等效于 Java 的


String.format("%1$s -- %2$s -- %3$s", ob1, ob2, ob3)

请注意从 1 开始的索引,“s”表示使用 .toString() 转换为字符串。还有许多其他可用的转换和格式选项:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax


答案 2

看看 String.formatPrintStream.format 方法。

两者都基于java.util.Formatter类

字符串格式示例:

Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

System.out.format 示例:

// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"