温馨提示×

C#中String.Format的使用方法是什么

c#
小亿
82
2024-04-29 09:32:44
栏目: 编程语言

在C#中,String.Format方法用于将指定的格式和参数值转换为一个格式化的字符串。其基本语法如下:

string formattedString = string.Format("格式字符串", 参数1, 参数2, ...);

其中,"格式字符串"是一个包含占位符和格式说明符的字符串,用于指定参数值在输出字符串中的格式。参数1、参数2等是要格式化的值。

例如,下面是一个简单的示例:

string name = "Alice";
int age = 30;
string formattedString = string.Format("My name is {0} and I am {1} years old.", name, age);
Console.WriteLine(formattedString);

运行以上代码,输出结果为:

My name is Alice and I am 30 years old.

在格式字符串中,{0}、{1}等表示参数值的位置,可以根据需要在字符串中对应不同的参数值。格式字符串还可以包含格式说明符,如"{0:C}"表示将第一个参数值格式化为货币格式。

0