C#中的String类型
时间: 2025-06-25 08:03:56 浏览: 12
### C# 中 `String` 类型的使用说明、特性以及常用方法
#### 1. **`String` 是引用类型**
尽管 `string` 表现得像值类型,但它实际上是引用类型。这意味着当我们将一个字符串赋值给另一个变量时,实际上是在复制引用而非数据本身[^1]。
然而,`string` 的行为与其他引用类型不同,它具有不可变性(Immutability)。一旦创建了一个字符串对象,其内容就不能被修改。任何看似改变字符串的操作都会返回一个新的字符串实例,而原始字符串保持不变[^1]。
```csharp
static void Main(string[] args)
{
string original = "Hello";
string modified = original.Replace("H", "J");
Console.WriteLine(original); // 输出: Hello
Console.WriteLine(modified); // 输出: Jello
}
```
#### 2. **字符串池优化**
为了节省内存并提升性能,C# 提供了字符串驻留(Interning)机制。每当定义新的字符串字面量时,编译器会先检查全局字符串池中是否存在相同的内容。如果已存在,则不会分配新空间;反之则加入到池中[^2]。
此功能对于频繁重复使用的短字符串非常有用,可以有效降低资源消耗。
```csharp
string s1 = "Test";
string s2 = "Test";
Console.WriteLine(object.ReferenceEquals(s1, s2)); // true
```
#### 3. **常见方法概述**
以下是几个常用的 `System.String` 成员函数及其作用:
- **Concat**: 将多个字符串连接成单个字符串。
```csharp
string result = string.Concat("A", "B", "C"); // ABC
```
- **Compare/CompareTo**: 比较两个字符串大小关系。
```csharp
int comparisonResult = string.Compare("Apple", "Banana"); // 负数表示前者小于后者
```
- **Contains**: 判断子串是否存在于当前字符串内。
```csharp
bool containsIt = "Example".Contains("amp"); // true
```
- **EndsWith/StartsWith**: 测试字符串开头或结尾特定模式匹配情况。
```csharp
bool endsCorrectly = "Filename.txt".EndsWith(".txt"); // true
```
- **Format**: 创建格式化后的复合字符串。
```csharp
string greeting = string.Format("Hi {0}, welcome!", "John Doe");
```
- **IndexOf/LastIndexOf**: 查找指定字符首次出现位置或者最后一次的位置索引。
```csharp
int firstPosition = "abcdefgabc".IndexOf('a'); // 返回 0
int lastPosition = "abcdefgabc".LastIndexOf('b'); // 返回 8
```
- **Insert**: 向现有字符串某处插入另一段文字。
```csharp
string insertedText = "World!".Insert(0, "Hello "); // Hello World!
```
- **Join**: 把数组中的元素通过分隔符组合起来形成单一字符串。
```csharp
string joinedItems = string.Join(",", new[]{"Red","Green","Blue"}); // Red,Green,Blue
```
- **Length Property**: 获取字符串长度属性。
```csharp
int lengthOfString = "Sample Text".Length; // 11
```
- **ToLower()/ToUpper()**: 字母转换为小写形式或大写形式。
```csharp
string lowerCaseVersion = "MIXED CASE".ToLower(); // mixed case
```
- **Replace**: 替换所有符合条件的部分为目标替代物。
```csharp
string replacedContent = "Original Content".Replace("Original", "New"); // New Content
```
- **Split**: 根据界定符拆分成若干部分存入集合里。
```csharp
string[] parts = "One-Two-Three-Four".Split('-');
foreach (var part in parts) {
Console.Write(part + ", ");
}
// One, Two, Three, Four,
```
- **Substring**: 截取一段连续区域作为独立的新字符串。
```csharp
string subStr = "abcdefghij".Substring(3,4); // defg
```
- **Trim():** 去除首尾空白字符(包括制表符等不可见符号),还有专门针对某些特殊字符版本如 TrimStart 和 TrimEnd。
```csharp
string cleanInput = "\t Some Input \n ".Trim(); // 'Some Input'
```
---
阅读全文
相关推荐











