?????Java??String.format()
??????????????????,????????????????????????????????String.format()
?????:
- ?????:
String name = "Alice"; int age = 30; String formattedString = String.format("My name is %s and I am %d years old.", name, age); System.out.println(formattedString);
??:
My name is Alice and I am 30 years old.
- ???????:
double pi = 3.141592653589793; String formattedPi = String.format("Pi is approximately %.2f", pi); System.out.println(formattedPi);
??:
Pi is approximately 3.14
??????,%.2f
?????????????????????
- ??????:
String.format()
?????????????????,?????%d
??????,%f
???????,%s
?????????
int daysOfWeek = 7; String days = String.format("d", daysOfWeek); // ??0?????? System.out.println(days); // ??: 07
??????,d
??????????????????,??????,??0???
- ???????:
?Java 5??,?????????????????????????????????????
String name = "Alice"; int age = 30; String formattedString = String.format("My name is %s and I am %d years old.", name, age); System.out.println(formattedString); // ??????? formattedString = String.format("My name is {name} and I am {age} years old.", name=name, age=age); System.out.println(formattedString);
??:????????????,?????????????????????????,??Java?String.format()
???????????????,??????Java 5????????Map
?????????????
??????????(??Map
):
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { String name = "Alice"; int age = 30; Mapvalues = new HashMap<>(); values.put("name", name); values.put("age", age); String formattedString = String.format("My name is %s and I am %d years old.", name, age); System.out.println(formattedString); formattedString = String.format("My name is {name} and I am {age} years old.", values); System.out.println(formattedString); } }
??:
My name is Alice and I am 30 years old. My name is {name} and I am {age} years old.
??????????,???????Map
???????????????,??????{name}
?{age}
?????????