好的,以下是 C# 中 string 类和 StringBuilder 类的所有常用和不常用的方法的完整列表,并逐行解释每个方法的用法和作用。
1. string 类的所有方法
1.1. Length
获取字符串的长度。
string str = "Hello, World!"; // 定义一个字符串变量 str,内容为 "Hello, World!"
int length = str.Length; // 获取字符串的长度,并将其赋值给变量 length
Console.WriteLine(length); // 输出字符串的长度,结果为 13
1.2. Substring
从字符串中提取子字符串。
string str = "Hello, World!"; // 定义一个字符串变量 str,内容为 "Hello, World!"
string substr = str.Substring(7, 5); // 从索引 7 开始提取 5 个字符,结果为 "World"
Console.WriteLine(substr); // 输出提取的子字符串,结果为 "World"
1.3. IndexOf
查找子字符串在字符串中的位置。
string str = "Hello, World!"; // 定义一个字符串变量 str,内容为 "Hello, World!"
int index = str.IndexOf("World"); // 查找子字符串 "World" 在 str 中的索引位置,结果为 7
Console.WriteLine(index); // 输出索引位置,结果为 7
1.4. LastIndexOf
查找子字符串在字符串中最后一次出现的位置。
string str = "Hello, World! World!"; // 定义一个字符串变量 str,内容为 "Hello, World! World!"
int lastIndex = str.LastIndexOf("World"); // 查找子字符串 "World" 在 str 中最后一次出现的索引位置,结果为 14
Console.WriteLine(lastIndex); // 输出索引位置,结果为 14
1.5. Contains
检查字符串是否包含子字符串
string str = "Hello, World!"; // 定义一个字符串变量 str,内容为 "Hello, World!"
bool contains = str.Contains("World"); // 检查 str 是否包含子字符串 "World",结果为 true
Console.WriteLine(contains); // 输出检查结果,结果为 true
1.6. Replace
替换字符串中的子字符串。
string str = "Hello, World!"; // 定义一个字符串变量 str,内容为 "Hello, World!"
string newStr = str.Replace("World", "C#"); // 将子字符串 "World" 替换为 "C#",结果为 "Hello, C#!"
Console.WriteLine(newStr); // 输出替换后的字符串,结果为 "Hello, C#!"
1.7. ToUpper 和 ToLower
将字符串转换为大写或小写。
string str = "Hello, World!"; // 定义一个字符串变量 str,内容为 "Hello, World!"
string upperStr = str.ToUpper(); // 将字符串转换为大写,结果为 "HELLO, WORLD!"
string lowerStr = str.ToLower(); // 将字符串转换为小写,结果为 "hello, world!"
Console.WriteLine(upperStr); // 输出大写字符串,结果为 "HELLO, WORLD!"
Console.WriteLine(lowerStr); // 输出小写字符串,结果为 "hello, world!"
1.8. Trim, TrimStart, TrimEnd
去除字符串两端或指定方向的空白字符。
string str = " Hello, World! "; // 定义一个字符串变量 str,内容为 " Hello, World! "
string trimmedStr = str.Trim(); // 去除字符串两端的空白字符,结果为 "Hello, World!"
Console.WriteLine(trimmedStr); // 输出去除空白字符后的字符串,结果为 "Hello, World!"
1.9. Split
将字符串分割成子字符串数组。
string str = "apple,banana,cherry"; // 定义一个字符串变量 str,内容为 "apple,banana,cherry"
string[] fruits = str.Split(',&