在Java中,除了可以使用printf方法对字符串进行格式化输出外,还有其他几种常用的方法可以用来格式化字符串:
String formattedString = String.format("Hello, %s! Today is %tF", "Alice", new Date());
System.out.println(formattedString);
String pattern = "Hello, {0}! Today is {1,date,yyyy-MM-dd}";
String formattedString = MessageFormat.format(pattern, "Alice", new Date());
System.out.println(formattedString);
StringJoiner joiner = new StringJoiner(", ", "Hello, ", "!");
joiner.add("Alice").add("Bob");
String formattedString = joiner.toString();
System.out.println(formattedString);
StringBuilder sb = new StringBuilder();
sb.append("Hello, ").append("Alice").append("!");
String formattedString = sb.toString();
System.out.println(formattedString);
这些方法都可以达到类似于printf方法的格式化效果,选择合适的方法取决于具体的需求和习惯。