C# string的格式
时间: 2024-11-22 21:36:55 浏览: 26
在C#中,`string` 类型提供了多种格式化字符串的方法,使得我们可以按照预设的规则插入变量或表达式的值。最常用的是 `string.Format()`、`StringBuilder.AppendFormat()` 和 ` interpolated strings`。
1. **`string.Format()`**:这是一种基于占位符的格式化方式,语法是 `{0}`、`{1}`、`{2}`...对应位置的参数,例如:
```csharp
string name = "Alice";
int age = 30;
string formattedString = string.Format("My name is {0} and I am {1} years old.", name, age);
```
2. **`StringBuilder.AppendFormat()`**:类似 `string.Format()`, 但它返回的是 `StringBuilder` 对象,适用于大量数据连接或需要多次修改的情况。
3. **Interpolated Strings (C# 6 及以后)**:也称为元组字符串,更简洁明了,可以直接在大括号内编写表达式:
```csharp
string ageAgain = $"My name is {name}, and I am {age} years old.";
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)