Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# string.format

作者:二分醒amor   发布日期:2026-06-27   浏览:73

// 使用 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 (取决于当前时间)

解释说明:

  1. 基本用法string.Format 方法允许你通过占位符 {0}, {1} 等来插入变量值。第一个参数是格式化字符串,后面的参数是要插入到占位符中的值。
  2. 使用索引和格式化:你可以通过在占位符中指定格式(如 {0:C2}),来控制输出的格式。这里的 C2 表示货币格式,并保留两位小数。
  3. 复杂格式化:可以对日期时间进行格式化,例如 {0:yyyy-MM-dd}{0:HH:mm:ss} 分别表示年月日和时分秒的格式。

如果你需要更多关于 string.Format 的详细信息或有其他问题,请随时告诉我!

上一篇:c#多线程

下一篇:c# 字典

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站