c# 格式化输出字符串
时间: 2023-07-25 14:38:37 浏览: 58
在 C# 中,可以使用 `string.Format()` 方法来格式化输出字符串。该方法使用类似占位符的方式来指定输出字符串中的特定部分。以下是一个简单的例子:
```csharp
int num = 10;
string name = "John";
double price = 12.5;
string output = string.Format("The number is {0}, the name is {1}, and the price is {2:C}.", num, name, price);
Console.WriteLine(output);
```
输出结果为:
```
The number is 10, the name is John, and the price is $12.50.
```
在上面的代码中,`{0}`、`{1}` 和 `{2}` 是占位符,分别表示参数列表中的第一个、第二个和第三个参数。冒号后面的 `C` 表示将 `price` 参数格式化为货币形式。
除了上述示例中的格式化方式外,还有其他一些常用的格式化选项,例如日期时间格式化、数字格式化等等。您可以参考 C# 文档了解更多信息。
相关问题
c# 字符串格式化输出
在 C# 中,可以使用字符串格式化输出来控制文本的显示格式。以下是几个常见的字符串格式化输出示例:
1. 占位符格式化
使用占位符 `{0}` 可以在字符串中插入变量,可以使用多个占位符来插入多个变量。
```C#
string name = "John";
int age = 30;
string message = string.Format("My name is {0} and I am {1} years old.", name, age);
Console.WriteLine(message);
```
输出:`My name is John and I am 30 years old.`
2. 对齐格式化
可以使用对齐格式化来控制输出文本的对齐方式,例如:
```C#
string name = "John";
int age = 30;
string message = string.Format("{0,-10} | {1,5}", name, age);
Console.WriteLine(message);
```
输出:`John | 30`
3. 格式控制符
可以使用格式控制符来控制输出文本的格式,例如:
```C#
double price = 19.99;
string message = string.Format("The price is: {0:C}", price);
Console.WriteLine(message);
```
输出:`The price is: $19.99`
以上是几个常见的字符串格式化输出示例,还有很多其他的格式化选项可以使用,具体可以参考C#的官方文档。
C#字符串格式化
C#中的字符串格式化可以使用字符串插值(string interpolation)或者格式化字符串(format string)两种方式实现。
1. 字符串插值
字符串插值是在字符串中插入表达式或变量的值的一种简单方法。使用字符串插值时,需要在字符串前面加上 $ 符号,然后用花括号 {} 包含需要插入的表达式或变量。
例如:
```csharp
int age = 25;
string name = "Tom";
string message = $"My name is {name} and I am {age} years old.";
```
输出结果为:My name is Tom and I am 25 years old.
2. 格式化字符串
格式化字符串是通过指定占位符和参数来格式化字符串的一种方法。可以使用 String.Format 方法或者 $ 符号加花括号 {} 来实现。
例如:
```csharp
int age = 25;
string name = "Tom";
string message = String.Format("My name is {0} and I am {1} years old.", name, age);
```
或者:
```csharp
int age = 25;
string name = "Tom";
string message = $"My name is {name} and I am {age} years old.";
```
两种方式输出结果相同:My name is Tom and I am 25 years old.
除了基本类型,还可以使用格式字符串指定更复杂的格式,例如日期时间格式、货币格式等。
例如:
```csharp
DateTime now = DateTime.Now;
string message = $"The current time is {now:yyyy-MM-dd HH:mm:ss}.";
```
输出结果为:The current time is 2021-05-25 15:30:00.