Hady Hallak
Hady Hallak

Reputation: 347

How to Get rid of \r\n in a string

I'm trying to get messages from Gmail in C#

but the message body comes like this "\r\n\r\nBODY\r\n\r\n"

How can I get the "BODY" out of the string ?

I tried to loop through it but I found out that when looping the "\r" becomes a " "

Upvotes: 5

Views: 3173

Answers (5)

creativedave
creativedave

Reputation: 1

This works for me:

    string result= rawString.Replace(@"\r\n", " ").Trim().Replace(Environment.NewLine, " ").Replace("\n", " ");

Upvotes: 0

user2273202
user2273202

Reputation:

When a user writes some text in a file, the Editor automatically appends CR|LF after each line. CR or Carriage Return is denoted as \r
LF or Line Feed is denoted as \n

These are normally invisible to us, but while reading a text file using some code process it also captures these escape sequences.

To avoid these character you can easily replace them using builtin C# function Replace method

You can use following code to get rid from \r and \n

str = str.Replace("\r\n","");

This will first find out all combined \r\n characters and then replaces this string with "" (Blank string).

Upvotes: 0

lewis
lewis

Reputation: 253

body = body.Replace("\r\n", string.Empty);

Upvotes: 2

David
David

Reputation: 218837

You can use String.Trim() to remove all leading and trailing whitespace form a given string. Something like this:

var body = inputString.Trim();

This would cover /r/n characters, as well as any other whitespace.

Upvotes: 17

Yoav
Yoav

Reputation: 3386

try this:

string after = text.Replace(Environment.NewLine, "");

Upvotes: 7

Related Questions