除去换行使用C# [英] Removing line breaks using C#

查看:206
本文介绍了除去换行使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到来自名为描述数据库字段的字符串,它有换行符。它看起来是这样的:

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

项目的标题

说明进入这里。这项目的说明。

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;
}

请建议的解决方案。

问候, 阿西夫·哈米德

Regards, Asif Hameed

推荐答案

主要的原因是,您使用的是<一href="http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-does-an-before-the-start-of-a-string-literal-mean.aspx">verbatim字符串(pfaced与 @ $ P $),并用文字结束\ 。其结果是,替换将最终寻求替换的字符序列 \ 研究 \ N \ ,而不是一个新行。

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.

这应该修复它:

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

但更地道(便携式)是:

But more idiomatic (and portable) would be:

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

(编辑:这当然是假定该写入到数据库的系统使用相同的新行约定,从它或翻译透明地发生读取系统。如果不是这种情况下,你当然会。更好使用你想用它来重新present新行的实际字符序列。)

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

这篇关于除去换行使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆