c#字符串去除尾部所有的\0
时间: 2023-08-07 15:38:42 浏览: 360
如果要去除字符串尾部所有的 `\0`,可以使用 `TrimEnd` 方法结合 `Reverse` 方法和 `IndexOf` 方法实现。示例如下:
```csharp
string str = "hello world\0\0\0";
int index = str.Reverse().IndexOf('\0');
string trimmedStr = index >= 0 ? str.Substring(0, str.Length - index - 1) : str;
Console.WriteLine(trimmedStr); // 输出 "hello world"
```
在上述示例中,我们首先使用 `Reverse` 方法将字符串反转,然后使用 `IndexOf` 方法查找字符串中第一个 `\0` 的位置。如果找到了,则使用 `Substring` 方法截取字符串尾部 `\0` 之前的部分,即为去除尾部所有的 `\0` 后的字符串。如果没有找到,则说明字符串中没有 `\0`,直接返回原字符串。
相关问题
c#字符串去除尾部\0
在 C# 中,可以使用 `TrimEnd` 方法去除字符串末尾的特定字符,包括 `\0`。示例如下:
```csharp
string str = "hello world\0";
string trimmedStr = str.TrimEnd('\0');
Console.WriteLine(trimmedStr); // 输出 "hello world"
```
`TrimEnd` 方法接受一个字符数组作为参数,表示要去除的字符。在上述示例中,我们将 `\0` 作为参数传入 `TrimEnd` 方法,实现了去除字符串末尾的 `\0`。
c#字符串去除所有\0
如果要去除字符串中所有的 `\0`,可以使用 `Replace` 方法将其替换为空字符串。示例如下:
```csharp
string str = "he\0llo\0 \0world\0";
string replacedStr = str.Replace("\0", "");
Console.WriteLine(replacedStr); // 输出 "hello world"
```
在上述示例中,我们将 `\0` 作为参数传入 `Replace` 方法,将其替换为空字符串,实现了去除字符串中所有的 `\0`。