C# 去掉字符串全部的\r\n和空格
时间: 2023-06-30 11:23:09 浏览: 462
可以使用 C# 中的 `Replace` 和 `Trim` 方法来去掉字符串全部的 `\r\n` 和空格。具体操作如下:
```csharp
string str = " hello world\r\n ";
str = str.Replace("\r\n", "").Trim();
```
这样就可以将字符串 `str` 中的全部 `\r\n` 和空格去掉了。
相关问题
C# 去除字符串中空格
在C#中,你可以使用`String.Replace()`、`Trim()`或者`Regex.Replace()`方法去除字符串中的空格。以下是三种常见方法:
1. **Replace()**方法:
```csharp
string str = " Hello World ";
string result = str.Replace(" ", "");
```
这会将所有的空格替换为空字符串。
2. **Trim()**方法:
```csharp
string str = " Hello World ";
string result = str.Trim();
```
这个方法只会去掉字符串开头和结尾的空格。
3. **正则表达式Replace()**:
```csharp
using System.Text.RegularExpressions;
string str = " Hello World ";
string pattern = @"\s+";
string result = Regex.Replace(str, pattern, "");
```
这里`\s+`匹配一个或多个连续的空格字符,并将其替换为无。
C#去除字符串中的空格
在C#中,可以使用`Replace`方法来去除字符串中的空格。以下是一个示例代码:
```csharp
string input = "Hello World";
string output = input.Replace(" ", "");
Console.WriteLine(output); // 输出:HelloWorld
```
在上述代码中,`Replace`方法用空字符串`""`替换了输入字符串中的空格,从而实现了去除空格的效果。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)