String.format
时间: 2023-06-24 17:08:37 浏览: 55
String.format() 是 Java 中的一个方法,用于将指定的格式化字符串和参数列表组合成一个新的字符串。它的语法如下:
```
String.format(String format, Object... args)
```
其中,第一个参数 `format` 是一个字符串,包含了格式说明符和普通字符,用于指定输出的格式;第二个参数 `args` 是可变参数列表,用于提供要格式化的值。
例如,以下代码使用 String.format() 将整数、浮点数和字符串格式化成指定格式的字符串:
```java
int num = 42;
double pi = 3.1415926;
String name = "Alice";
String formatted = String.format("The answer is %d, the value of pi is %.2f, and the name is %s.", num, pi, name);
System.out.println(formatted);
// Output:
// The answer is 42, the value of pi is 3.14, and the name is Alice.
```
在格式字符串中,%d 表示整数,%.2f 表示保留两位小数的浮点数,%s 表示字符串。在执行 String.format() 方法时,这些格式说明符会被替换成实际的值,生成最终的字符串。
相关问题
string.format
String.format is a method that is used to format a string in a specific way. It is available in many programming languages and is used to create a new string by inserting variables or values into a specific format.
The basic syntax of string.format is:
string.format(format, ...)
Here, format is a string that contains placeholders for the values that will be inserted, and the ellipsis (...) represents the values that will be inserted into the placeholders.
For example, in Lua, the following code:
age = 25
name = "John"
print(string.format("%s is %d years old.", name, age))
will output:
John is 25 years old.
Similarly, in Python, the following code:
age = 25
name = "John"
print("{} is {} years old.".format(name, age))
will output:
John is 25 years old.
string.Format
string.Format 是一个用于格式化字符串的方法,它可以将多个参数按照指定的格式组合成一个字符串。它的语法如下:
string.Format(string format, params object[] args)
其中,format 参数是一个包含格式占位符的字符串,args 参数是一个包含要格式化的对象的数组。格式占位符可以使用大括号 {} 表示,其中可以包含一个可选的索引或格式字符串。例如:
string s = string.Format("Hello, {0}! Today is {1:d}", "Alice", DateTime.Now);
Console.WriteLine(s); // 输出 "Hello, Alice! Today is 2022-05-25"
在上面的例子中,{0} 和 {1:d} 是格式占位符,分别代表第一个和第二个参数。第二个占位符使用了格式字符串 ":d",表示要将日期格式化为短日期格式。