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

c# string format

作者:ι错过了   发布日期:2025-05-27   浏览:56

// 示例代码:使用 C# 中的 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. 使用命名参数
string formattedStringWithNamedParameters = string.Format("Name: {name}, Age: {age}", name, age);
Console.WriteLine(formattedStringWithNamedParameters); // 输出: Name: Alice, Age: 30

// 3. 格式化数字
double price = 1234.5678;
string formattedPrice = string.Format("Price: {0:C}", price);
Console.WriteLine(formattedPrice); // 输出: Price: $1,234.57 (根据区域设置)

// 4. 格式化日期
DateTime currentDate = DateTime.Now;
string formattedDate = string.Format("Today's Date: {0:yyyy-MM-dd}", currentDate);
Console.WriteLine(formattedDate); // 输出类似: Today's Date: 2023-10-05

// 5. 使用复合格式说明符
string complexFormat = string.Format("Value: {0:N2}%, Percentage: {1:P2}", 0.8765, 0.4567);
Console.WriteLine(complexFormat); // 输出: Value: 87.65%, Percentage: 45.67 %

解释说明:

  • string.Format 是 C# 中用于格式化字符串的方法。它允许你将多个值插入到一个字符串模板中。
  • {0}{1} 等是占位符,表示按顺序插入相应的参数。
  • 可以通过在占位符中添加格式说明符(如 C 表示货币格式,N2 表示带两位小数的数字格式)来控制输出格式。
  • 命名参数(如 {name}{age})可以提高代码的可读性,尤其是在参数较多时。

如果你需要更复杂的格式化需求,string.Format 提供了丰富的选项来满足不同的场景。

上一篇:c#foreach

下一篇:c#invoke

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c#高并发

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

Laravel 中文站