C# 字符串 - Format() 方法
C# 字符串 Format() 方法用于将指定字符串中的一个或多个格式项替换为给定对象的字符串表示形式。或者,我们可以将此方法声明为用于将变量、对象或表达式的值插入另一个字符串。
需要注意的是,此方法可以通过传递不同类型的参数进行重载。让我们看看它的基本语法 -
语法
以下是 C# 字符串的语法 Format() 方法 -
public static string Format (string format, params object[] args);
参数
此方法接受以下参数 -
- format:此参数指定所需的复合格式字符串。
- args:它表示包含零个或多个要格式化的对象的对象数组。
返回值
此方法返回一个字符串。这是格式的副本,其中使用参数的字符串表示形式代替格式项。
示例 1:基本字符串格式化
以下是Format()方法的基本示例,用于使用占位符格式化字符串 -
using System; class Program { static void Main() { int age = 25; string name = "Aman"; // 使用占位符格式化字符串 string result = string.Format("My name is {0} and I am {1} years old.", name, age); Console.WriteLine(result); } }
输出
以下是输出 -
My name is Aman and I am 25 years old.
示例 2:插入字符串
让我们来看另一个 Format() 方法的示例。这里,我们以一个格式字符串开始,然后是一个或多个将被转换为字符串并插入到指定位置的对象或表达式 -
using System; class Program { static void Main() { decimal temp = 20.4m; string s = String.Format("The temperature is {0}C.", temp); Console.WriteLine(s); } }
输出
以下是输出 -
The temperature is 20.4C.
示例 3:在格式字符串中使用索引
在此示例中,我们使用 Format() 方法在格式字符串中多次重复使用相同的参数 -
using System; class Program { static void Main() { int x = 5, y = 10; // 重复使用参数 string result = string.Format("First number: {0}, second number: {1}, sum: {2}", x, y, x + y); Console.WriteLine(result); } }
输出
以下是输出 -
First number: 5, second number: 10, sum: 15
示例 4:格式化数字和日期
在此示例中,我们使用 Format() 方法,通过格式说明符格式化数字和日期 -
using System; class Program { static void Main() { double price = 1234.567; DateTime currentDate = DateTime.Now; // 将数字格式化为小数点后 2 位,并格式化日期 string result = string.Format("The price is {0:C} and today's date is {1:D}.", price, currentDate); Console.WriteLine("Formated String"); Console.WriteLine(result); } }
输出
以下是输出 -
Formated String The price is $1,234.57 and today's date is Wednesday, January 8, 2025.