// 使用 String.Format 方法格式化字符串的示例
// 示例 1: 基本用法
string name = "Alice";
int age = 30;
string formattedString = string.Format("Name: {0}, Age: {1}", name, age);
Console.WriteLine(formattedString); // 输出: Name: Alice, Age: 30
// 示例 2: 使用索引和格式化
double price = 1234.5678;
string formattedPrice = string.Format("The price is {0:C2}", price);
Console.WriteLine(formattedPrice); // 输出: The price is $1,234.57 (取决于区域设置)
// 示例 3: 复杂格式化
DateTime now = DateTime.Now;
string formattedDateTime = string.Format("Today is {0:yyyy-MM-dd} and the time is {0:HH:mm:ss}", now);
Console.WriteLine(formattedDateTime); // 输出: Today is 2023-10-05 and the time is 14:30:45 (取决于当前时间)
string.Format 方法允许你通过占位符 {0}, {1} 等来插入变量值。第一个参数是格式化字符串,后面的参数是要插入到占位符中的值。{0:C2}),来控制输出的格式。这里的 C2 表示货币格式,并保留两位小数。{0:yyyy-MM-dd} 和 {0:HH:mm:ss} 分别表示年月日和时分秒的格式。如果你需要更多关于 string.Format 的详细信息或有其他问题,请随时告诉我!
上一篇:c#多线程
下一篇:c# 字典
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站