简体   繁体   English

如何从 C# 中的字符串中删除 '\\0'?

[英]How to Remove '\0' from a string in C#?

I would like to know how to remove '\\0' from a string.我想知道如何从字符串中删除 '\\0' 。 This may be very simple but it's not for me since I'm a new C# developer.这可能非常简单,但不适合我,因为我是一名新的 C# 开发人员。

I've this code:我有这个代码:

public static void funcTest (string sSubject, string sBody)
{
    Try
      {
        MailMessage msg = new MailMessage(); // Set up e-mail message.
        msg.To = XMLConfigReader.Email;
        msg.From = XMLConfigReader.From_Email;
        msg.Subject = sSubject;
        msg.body="TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\r\n";     
      }
    catch (Exception ex) 
      {
        string sMessage = ex.Message;     
        log.Error(sMessage, ex);   
      }
}

But what I want is:但我想要的是:

msg.body="TestStrg.\r\nTest\r\n";

So, is there a way to do this with a simple code?那么,有没有办法用简单的代码来做到这一点?

It seems you just want the string.Replace function (static method).看来您只想要string.Replace函数(静态方法)。

var cleaned = input.Replace("\0", string.Empty);

Edit: Here's the complete code, as requested:编辑:这是完整的代码,根据要求:

public static void funcTest (string sSubject, string sBody)
{
    try
    {
        MailMessage msg = new MailMessage();
        msg.To = XMLConfigReader.Email;
        msg.From = XMLConfigReader.From_Email;
        msg.Subject = sSubject;
        msg.Body = sBody.Replace("\0", string.Empty);
    }
    catch (Exception ex) 
    {
        string sMessage = ex.Message;     
        log.Error(sMessage, ex);   
    }
}

我使用: something.TrimEnd('\\0')

你只需要更换

msg.body="TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\r\n".Replace("\0", string.Empty);    

这是 Bing 中的第一个结果,它没有我喜欢的方法,即

string str = "MyString\0\0\0\0".Trim('\0');

尝试这个:

msg.Body = msg.Body.Replace("\0", "");

如果您使用 LINQ,结果可能会更快

str.TakeWhile(c => c != '\0');

保持愚蠢的简单=*

return stringValue.Substring(0, stringValue.IndexOf('\0'));
msg.body = sBody.Replace("\0", "");

I know I'm late here but, while String.Replace works most of the time I have found that I like the regex version of this much better and is more reliable in most cases我知道我迟到了,但是虽然 String.Replace 大部分时间都可以工作,但我发现我更喜欢这个的正则表达式版本,并且在大多数情况下更可靠

using System.Text.RegularExpressions;
...

 msg.body=Regex.Replace("TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\r\n","\0");
var str = "TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\r\n".Replace("\0", "");

String.Replace()将用空字符串替换所有\\0 ,从而删除它们。

这条线应该工作:

string result = Regex.Replace(input, "\0", String.Empty);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM