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\nTes开发者_运维技巧t\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);
}
}
I use: something.TrimEnd('\0')
This was the first result in Bing, and it didn't have my preferred method, which is
string str = "MyString\0\0\0\0".Trim('\0');
you just need to Replace it
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);
Try this:
msg.Body = msg.Body.Replace("\0", "");
It may have a faster result if you use LINQ
str.TakeWhile(c => c != '\0');
Linq has a better and faster performance.
msg.body = sBody.Replace("\0", "");
var str = "TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\r\n".Replace("\0", "");
String.Replace()
will replace all the \0
's with an empty string, thereby removing them.
Keep it stupidly simple =*
return stringValue.Substring(0, stringValue.IndexOf('\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");
This line should work:
string result = Regex.Replace(input, "\0", String.Empty);
精彩评论