Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 981
Davideg Avatar asked Aug 02 '10 12:08

Davideg


People also ask

What is the purpose of '\ 0 character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).

Why we use '\ 0 at the end of the string?

it is used to show that the string is completed.it marks the end of the string. it is mainly used in string type.by default string contain '\0\ character means it show the end of the character in string. end of the array contain ''\0' to stop the array memory allocation for string name.

How do I remove a character from a string in C?

We have removeChar() method that will take a address of string array as an input and a character which you want to remove from a given string. Now in removeChar(char *str, char charToRemove) method our logic is written.

Do all strings end in \0 C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'.


2 Answers

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);        } } 
like image 161
Noldorin Avatar answered Sep 29 '22 11:09

Noldorin


I use: something.TrimEnd('\0')

like image 22
Sith2021 Avatar answered Sep 29 '22 10:09

Sith2021