Removing line breaks using C#

守給你的承諾、 提交于 2019-12-21 08:07:28

问题


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


回答1:


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



回答2:


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

result = Regex.Replace(result, @"\r\n?|\n", " ");



回答3:


Your issue is the @ symbol. It is not necessary in this case.

You want

comments.Replace("\r\n", "");



回答4:


For removal of all newlines, regardless of environment or badly formed strings, I think that this is the simplest option:

var singleLineString = multilineString.Replace("\r", string.Empty).Replace("\n", string.Empty);



回答5:


use that code for replace new line

myString = myString.Replace(System.Environment.NewLine, "replacement text");



来源:https://stackoverflow.com/questions/8365719/removing-line-breaks-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!