String.format
时间: 2023-07-05 19:33:37 浏览: 39
String.format 是一个 Java 中用于格式化字符串的方法,它允许你将一个格式化字符串和一组参数作为输入,然后输出一个格式化后的字符串。
例如,以下代码将输出 "Hello, John!":
```
String name = "John";
String greeting = String.format("Hello, %s!", name);
System.out.println(greeting);
```
在这个例子中,"Hello, %s!" 是格式化字符串,%s 是一个占位符,表示将来会被替换成一个字符串。第二个参数 name 就是这个字符串的实际值。在调用 String.format 方法时,将格式化字符串和参数传递进去,方法会将占位符替换为实际值,然后返回一个格式化后的字符串。
String.format 方法支持多种占位符,包括 %d (整数), %f (浮点数), %c (字符), %b (布尔值) 等等。你可以在格式化字符串中使用多个占位符,并按顺序提供相应的参数。
相关问题
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",表示要将日期格式化为短日期格式。