c#中还有别的去除字符串前后的空格的方法
时间: 2023-12-11 07:04:37 浏览: 149
在 C# 中,除了 `Trim()` 方法以外,还有其他一些去除字符串前后空格的方法,包括:
1. `TrimStart()` 和 `TrimEnd()` 方法:分别用来去除字符串开头和结尾的空格;
2. `Trim(char[])` 方法:可以指定要去除的字符数组;
3. `TrimStart(char[])` 和 `TrimEnd(char[])` 方法:可以分别指定要去除的字符数组,并分别用来去除字符串开头和结尾的空格。
这些方法都能够去除字符串前后的空格或其他指定字符。使用方法和 `Trim()` 类似,只需在方法名后面加上括号和参数即可。例如:
```csharp
string str = " Hello world! ";
string trimmedStr = str.Trim(); // 去除前后空格
string trimmedStartStr = str.TrimStart(); // 去除开头空格
string trimmedEndStr = str.TrimEnd(); // 去除结尾空格
char[] trimChars = { ' ', '!', '?' };
string trimmedCharsStr = str.Trim(trimChars); // 去除前后空格和指定字符
string trimmedStartCharsStr = str.TrimStart(trimChars); // 去除开头空格和指定字符
string trimmedEndCharsStr = str.TrimEnd(trimChars); // 去除结尾空格和指定字符
```
需要注意的是,使用 `Trim()` 等方法去除字符串前后的空格时,会返回一个新的字符串,原字符串不会被修改。如果需要修改原字符串,可以将返回值重新赋给原字符串,例如:
```csharp
string str = " Hello world! ";
str = str.Trim(); // 去除前后空格,并将结果重新赋给 str
```
阅读全文
相关推荐


















