简体   繁体   中英

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

I would like to know how to remove '\\0' from a string. This may be very simple but it's not for me since I'm a new C# developer.

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).

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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