## 1. 字符串的基本概念
在C#中,字符串是用于表示文本数据的类型。字符串是由字符组成的不可变序列,每个字符在字符串中都有一个位置索引。字符串是`System.String`类的实例。
- **不可变性**:字符串一旦创建,其内容不能被修改。每次对字符串进行修改操作时,都会生成一个新的字符串实例。
- **索引**:字符串中的字符从索引`0`开始计数。例如,`"Hello"`中,`'H'`的索引为`0`,`'e'`的索引为`1`,依此类推。
## 2. 创建字符串
### 2.1 使用字面量
```
string greeting = "Hello, World!";
```
### 2.2 使用`new`关键字
```
string name = new string('a', 5); // 创建一个包含5个'a'的字符串:"aaaaa"
```
### 2.3 使用`String.Concat`方法
```
string result = string.Concat("Hello", " ", "World"); // "Hello World"
```
### 2.4 使用`String.Join`方法
```
string[] words = { "Hello", "World" };
string sentence = string.Join(" ", words); // "Hello World"
```
### 2.5 使用`StringBuilder`
```
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
string finalString = sb.ToString(); // "Hello World"
```
## 3. 字符串的常用方法
### 3.1 获取字符串长度
```
string text = "Hello";
int length = text.Length; // 5
```
### 3.2 字符串拼接
```
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"
```
### 3.3 字符串比较
```
string str1 = "apple";
string str2 = "banana";
bool isEqual = str1 == str2; // false
```
### 3.4 字符串转换为大写或小写
```
string original = "Hello, World!";
string upper = original.ToUpper(); // "HELLO, WORLD!"
string lower = original.ToLower(); // "hello, world!"
```
### 3.5 查找子字符串
```
string text = "Hello, World!";
int index = text.IndexOf("World"); // 7
bool contains = text.Contains("World"); // true
```
### 3.6 替换子字符串
```
string text = "Hello, World!";
string newText = text.Replace("World", "C#"); // "Hello, C#!"
```
### 3.7 截取字符串
```
string text = "Hello, World!";
string substring = text.Substring(7, 5); // "World"
```
### 3.8 分割字符串
```
string text = "apple,banana,cherry";
string[] fruits = text.Split(','); // ["apple", "banana", "cherry"]
```
### 3.9 去除空格
```
string text = " Hello, World! ";
string trimmed = text.Trim(); // "Hello, World!"
```
### 3.10 格式化字符串
```
string name = "John";
int age = 30;
string message = $"Hello, my name is {name} and I am {age} years old."; // "Hello, my name is John and I am 30 years old."
```
## 4. 字符串的不可变性
字符串是不可变的,这意味着每次对字符串进行修改操作时,都会创建一个新的字符串实例。例如:
```
string original = "Hello";
string modified = original + " World"; // 创建了一个新的字符串 "Hello World"
Console.WriteLine(original); // 仍然输出 "Hello"
Console.WriteLine(modified); // 输出 "Hello World"
```
## 5. 字符串的比较
### 5.1 按值比较
```
string str1 = "apple";
string str2 = "apple";
bool isEqual = str1 == str2; // true
```
### 5.2 按引用比较
```
string str1 = new string("apple");
string str2 = new string("apple");
bool isReferenceEqual = object.ReferenceEquals(str1, str2); // false
```
## 6. 字符串的常用操作示例
### 6.1 检查字符串是否为空
```
string text = "";
bool isEmpty = string.IsNullOrEmpty(text); // true
```
### 6.2 检查字符串是否为空或空白
```
string text = " ";
bool isNullOrWhiteSpace = string.IsNullOrWhiteSpace(text); // true
```