Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing line breaks using C#

I am getting a string from database field named 'Description' and it has line breaks. It looks like this:


Header of Items

Description goes here.This the description of items.


How can I remove the line breaks. I tried following function but It is not working:

public string FormatComments(string comments)
{
    string result = comments.Replace(@"\r\n\", "");
    result = result.Replace(" ", "");
    return result;
}

Please suggest solution.

Regards, Asif Hameed

like image 657
DotnetSparrow Avatar asked Dec 03 '11 05:12

DotnetSparrow


People also ask

What does \r do in C?

'\r' is the carriage return character.

How do you remove a new line in fgets?

Replacing a \n with a \0 at the end of a string is a way of "removing" the newline.

Does Rstrip remove newline?

The rstrip() method removes any trailing character at the end of the string. By using this method, we can remove newlines in the provided string value.


2 Answers

Have you tried using regular expressions? They are pretty good in handling these type of tasks

result = Regex.Replace(result, @"\r\n?|\n", " ");
like image 150
Denys Wessels Avatar answered Oct 23 '22 19:10

Denys Wessels


The primary reason is that you are using a verbatim string literal (prefaced with @) and ending it with a literal \. The result is that Replace will end up looking to replace the sequence of characters \, r, \, n,\ rather than a new-line.

This should fix it:

string result = comments.Replace("\r\n", ""); // Not idiomatic

But more idiomatic (and portable) would be:

string result = comments.Replace(Environment.NewLine, "");

(EDIT: This of course assumes that the systems that write to the DB use the same new-line conventions as the systems that read from it or that the translations happen transparently. If this is not the case, you would of course be better off using the actual character sequence you wish to use to represent a new-line.)

By the way, it appears you are trying to get rid of all white-space characters.

In which case you could do :

// Split() is a psuedo-overload that treats all whitespace
// characters as separators.
string result = string.Concat(comments.Split()); 
like image 29
Ani Avatar answered Oct 23 '22 19:10

Ani