C# 字符串常用方法

文章目录


前言

请注意,C#中的string是不可变的,这意味着每次对字符串进行操作时,都会返回一个新的字符串对象,而原始字符串不会被修改。


Length:获取字符串中字符的个数(不包括末尾的空字符)

string str = "Hello";
Console.WriteLine(str.Length); // 输出 5

ToLower() 和 ToUpper():将字符串转换为小写或大写形式

string str = "Hello";  
Console.WriteLine(str.ToLower()); // 输出 "hello"  
Console.WriteLine(str.ToUpper()); // 输出 "HELLO"

Substring(int startIndex, int length):从指定索引开始截取指定长度的子字符串

string str = "Hello World"; 
Console.WriteLine(str.Substring(6, 5)); // 输出 "World"

Remove(int startIndex, int length):从指定索引开始移除指定长度的字符

string str = "Hello World"; 
Console.WriteLine(str.Remove(6, 5)); // 输出 "Hello "

Replace(string oldValue, string newValue):替换字符串中的指定字符或子字符串

string str = "Hello World";  
Console.WriteLine(str.Replace('o', '0')); // 输出 "Hell0 W0rld"  
Console.WriteLine(str.Replace("World", "C#")); // 输出 "Hello C#"

Split(char[] separator, StringSplitOptions options) :根据指定的分隔符拆分字符串

string str = "Hello,World,C#";  
string[] parts = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);  
foreach (string part in parts)  
{  
    Console.WriteLine(part); // 输出 "Hello" "World" "C#"  
}

IndexOf(char value) 和 IndexOf(string value):查找指定字符或子字符串在字符串中第一次出现的位置

string str = "Hello World";  
Console.WriteLine(str.IndexOf('W')); // 输出 6  
Console.WriteLine(str.IndexOf("World")); // 输出 6

LastIndexOf(char value) 和 LastIndexOf(string value):查找指定字符或子字符串在字符串中最后一次出现的位置

string str = "abc abc abc";  
Console.WriteLine(str.LastIndexOf('a')); // 输出 9(最后一个 'a' 的位置)  
Console.WriteLine(str.LastIndexOf("abc")); // 输出 9(最后一个 "abc" 的位置)

Trim()、TrimStart() 和 TrimEnd():移除字符串开头、结尾或两端的空白字符(包括空格、制表符和换行符)

string str = "   Hello World   ";  
Console.WriteLine(str.Trim()); // 输出 "Hello World"  
Console.WriteLine(str.TrimStart()); // 输出 "Hello World   "  
Console.WriteLine(str.TrimEnd()); // 输出 "   Hello World"

Contains(string value):判断字符串是否包含指定的子字符串

string str = "Hello World"; 
Console.WriteLine(str.Contains("World")); // 输出 True

StartsWith(string value) 和 EndsWith(string value):判断字符串是否以指定的子字符串开始或结束

string str = "Hello World";  
Console.WriteLine(str.StartsWith("Hello")); // 输出 True  
Console.WriteLine(str.EndsWith("World")); // 输出 True

PadLeft(int totalWidth) 和 PadRight(int totalWidth):在字符串的左侧或右侧填充空格,直到达到指定的总宽度

string str = "123";  
Console.WriteLine(str.PadLeft(5)); // 输出 "   123"(左侧填充3个空格)  
Console.WriteLine(str.PadRight(5, '*')); // 输出 "123**"(右侧填充2个'*')

Join(string separator, params string[] values):将多个字符串连接成一个字符串,并使用指定的分隔符分隔它们

string[] words = { "Hello", "World", "C#" };  
string sentence = string.Join(", ", words);  
Console.WriteLine(sentence); // 输出 "Hello, World, C#"

Format(string format, params object[] args):格式化字符串,将指定的参数插入到格式字符串中

string name = "John";  
int age = 30;  
string formattedString = string.Format("Name: {0}, Age: {1}", name, age);  
Console.WriteLine(formattedString); // 输出 "Name: John, Age: 30"

IsNullOrEmpty(string value):判断字符串是否为空或null

string str = null; 
Console.WriteLine(string.IsNullOrEmpty(str)); // 输出 True

IsNullOrWhiteSpace(string value):判断字符串是否为空、null或仅包含空白字符

string str = " "; 
Console.WriteLine(string.IsNullOrWhiteSpace(str)); // 输出 True

Concat(params string[] values):连接多个字符串并返回一个新的字符串

string result = string.Concat("Hello", " ", "World"); Console.WriteLine(result); // 输出 "Hello World"

CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count):将字符串中的字符复制到指定的字符数组中

char[] charArray = new char[5];  
string str = "Hello";  
str.CopyTo(0, charArray, 0, 5);  
Console.WriteLine(new string(charArray)); // 输出 "Hello"(注意:超出字符串长度的部分不会被复制,保持默认值)

IndexOfAny(char[] anyOf) 和 LastIndexOfAny(char[] anyOf):查找字符数组中字符在字符串中第一次或最后一次出现的位置

string str = "Hello World";  
char[] chars = { 'o', 'W' };  
Console.WriteLine(str.IndexOfAny(chars)); // 输出 4('o'的位置)  
Console.WriteLine(str.LastIndexOfAny(chars)); // 输出 6('W'的位置)

PadLeft(int totalWidth, char paddingChar) 和 PadRight(int totalWidth, char paddingChar):在字符串的左侧或右侧填充指定的字符,直到达到指定的总宽度

string str = "123";  
Console.WriteLine(str.PadLeft(5, '*')); // 输出 "**123"(左侧填充2个'*')  
Console.WriteLine(str.PadRight(5, '*')); // 输出 "123**"(右侧填充2个'*')

Remove(int startIndex):从指定索引开始移除字符串的剩余部分

string str = "Hello World"; 
Console.WriteLine(str.Remove(6)); // 输出 "Hello "

Insert(int startIndex, string value):在指定索引处插入一个字符串

string str = "Hello"; 
Console.WriteLine(str.Insert(5, " World")); // 输出 "Hello World"

字符串插值(String Interpolation)(C# 6.0及更高版本):使用$符号和大括号{}来嵌入变量或表达式,从而创建格式化的字符串

int age = 30;  
string name = "Alice";  
string message = $"My name is {name} and I am {age} years old.";  
Console.WriteLine(message); // 输出 "My name is Alice and I am 30 years old."

<think>嗯,用户现在想了解C#字符串常用方法,我之前已经回答过如何用C#处理逗号分隔的字符串计算平均值,其中涉及了一些字符串处理的方法,比如Split、Trim和转换方法。现在需要根据用户提供的引用内容,结合之前的回答,总结出C#字符串常用方法。 首先,用户给的引用里提到了TrimStart、TrimEnd、Trim、Split、Replace、Concat、Join等方法。之前的回答中也用到了Split和Trim来处理输入字符串,还有TryParse进行转换。需要把这些方法整理出来,分门别类,可能分成转换类、清理类、分割拼接类、替换格式化类等。 用户可能希望有一个结构清晰的总结,每个方法有简要说明和示例代码。要注意引用中的内容,比如引用2和3提到了Trim相关的方法,Split,还有Concat和Join,这些都需要包含进去。同时,之前的回答里用到了Split和Trim,还有TryParse,所以转换方法也需要提到。 需要检查是否有遗漏的常用方法,比如Substring、Contains、StartsWith、EndsWith、IndexOf等,虽然用户提供的引用里没提到,但这些也是常用的,可能需要补充。但根据引用内容,用户可能更关注他们提到的那些方法,所以需要平衡。 另外,用户提到的引用1中提到了Parse方法,但之前的回答里用的是TryParse,需要指出两者的区别,比如Parse会抛异常,而TryParse更安全。这可能属于转换类的方法。 还要注意示例代码的正确性,比如Trim的使用,Split的参数,以及Join和Concat的区别。例如,Concat是拼接字符串,而Join是用分隔符连接数组。Split的多种用法,比如分割选项StringSplitOptions.RemoveEmptyEntries,避免空字符串。 可能需要将方法分类,比如: 1. 类型转换:Parse、TryParse、ToString 2. 空白处理:Trim、TrimStart、TrimEnd 3. 分割与拼接:Split、Join、Concat 4. 替换与格式化:Replace、ToLower、ToUpper、格式化输出 5. 其他常用:Contains、Substring、IndexOf等 但根据引用内容,用户提供的引用没有提到Contains等方法,所以可能需要根据之前的回答和引用内容来决定是否包含。用户的问题明确是“常用方法总结”,所以应该尽量全面,但重点放在引用中提到的方法。 需要确保每个方法都有示例代码,并且代码符合C#语法。例如,在Split中使用StringSplitOptions.RemoveEmptyEntries来避免空元素,这在处理用户输入时很实用,比如多个逗号的情况。 另外,格式化输出在之前的回答中提到过ToString("F2"),这也需要包含在格式化部分。引用3中提到的ToLower和ToUpper,以及Replace,都需要举例说明。 最后,相关问题部分需要考虑用户可能进一步的问题,比如如何选择Parse和TryParse,性能优化,处理空值等,这些都是之前回答中涉及的,或者引用中提到的方法可能引发的问题。</think>### C# 字符串常用方法总结 以下是C#字符串处理的常用方法分类整理,结合类型转换、清理、分割、拼接等核心场景,并附示例代码说明: --- #### 一、**类型转换方法** 1. **`Parse` 与 `TryParse`** - `Parse`:将字符串转换为数值类型(可能抛出异常) ```csharp int num = int.Parse("123"); // 成功返回123 // int.Parse("abc"); // 抛出FormatException[^1] ``` - `TryParse`:安全转换(推荐使用) ```csharp bool success = int.TryParse("123", out int result); // success=true, result=123 ``` 2. **`ToString`** 将任意类型转为字符串,支持格式化: ```csharp double value = 3.1415; string str1 = value.ToString(); // "3.1415" string str2 = value.ToString("F2"); // "3.14"[^2] ``` --- #### 二、**空白处理** 1. **`Trim()`** 去除首尾空格或指定字符: ```csharp string str = " Hello "; Console.WriteLine($"-{str.Trim()}-"); // 输出:-Hello-[^3] ``` 2. **`TrimStart()` / `TrimEnd()`** 仅处理开头或结尾: ```csharp string str = " text "; string trimmedStart = str.TrimStart(); // "text " string trimmedEnd = str.TrimEnd(); // " text" ``` --- #### 三、**分割与拼接** 1. **`Split()`** 按分隔符分割字符串为数组: ```csharp string input = "A,B,C"; string[] parts = input.Split(','); // ["A", "B", "C"] // 过滤空值 string[] filtered = input.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); ``` 2. **`Join()`** 连接字符串数组: ```csharp string[] arr = {"你", "我", "他"}; string joined = string.Join("和", arr); // "你和我和他"[^3] ``` 3. **`Concat()`** 直接拼接多个字符串: ```csharp string s = string.Concat("Hello", " ", "World"); // "Hello World" ``` --- #### 四、**替换与格式化** 1. **`Replace()`** 替换子字符串: ```csharp string original = "Hello World"; string replaced = original.Replace("World", "C#"); // "Hello C#" ``` 2. **大小写转换** ```csharp string mixedCase = "AbCdEf"; string lower = mixedCase.ToLower(); // "abcdef" string upper = mixedCase.ToUpper(); // "ABCDEF"[^3] ``` --- #### 五、**其他常用方法** 1. **`Contains()`** 检查子字符串是否存在: ```csharp bool hasWord = "C# Programming".Contains("Pro"); // true ``` 2. **`Substring()`** 截取子字符串: ```csharp string str = "ABCDEF"; string sub = str.Substring(2, 3); // "CDE"(从索引2开始取3个字符) ``` 3. **`IndexOf()`** 查找字符/子串位置: ```csharp int index = "Hello".IndexOf('e'); // 1(索引从0开始) ``` --- ### 代码示例:综合应用 ```csharp // 处理用户输入并拼接结果 string input = " apple, banana, , cherry "; string[] fruits = input.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim().ToUpper()) .ToArray(); string output = string.Join(" | ", fruits); // "APPLE | BANANA | CHERRY" ``` --- ### 选择建议 - **安全转换**:优先使用 `TryParse` 避免异常[^1] - **空值处理**:`Split` 时添加 `StringSplitOptions.RemoveEmptyEntries` - **性能优化**:大量字符串操作建议使用 `StringBuilder` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sky-stars

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值