如何消除字符串中的所有换行符? [英] How to eliminate ALL line breaks in string?

查看:145
本文介绍了如何消除字符串中的所有换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要摆脱出现在字符串中的所有换行符(来自db). 我使用下面的代码来做到这一点:

I have a need to get rid of all line breaks that appear in my strings (coming from db). I do it using code below:

value.Replace("\r\n", "").Replace("\n", "").Replace("\r", "")

我可以看到至少有一个字符像行尾一样幸存了下来.字符代码为 8232 .

I can see that there's at least one character acting like line ending that survived it. The char code is 8232.

我很la脚,但是我必须说这是我第一次很高兴看到这个字符.显然,我可以直接替换此char,但是我正在考虑将当前方法(基于替换"\ r"和"\ n"的组合)扩展到更牢固的内容,因此它不仅包括' 8232'char,还有我找不到的所有其他字符.

It's very lame of me, but I must say this is the first time I have a pleasure of seeing this char. It's obvious that I can just replace this char directly, but I was thinking about extending my current approach (based on replacing combinations of "\r" and "\n") to something much more solid, so it would not only include the '8232' char but also all others not-found-by-me yet.

您有解决这种问题的防弹方法吗?

Do you have a bullet-proof approach for such a problem?

EDIT#1:

在我看来,有几种可能的解决方案:

It seems to me that there are several possible solutions:

  1. 使用Regex.Replace
  2. 如果是IsSeparator或IsControl,则删除所有字符
  3. 如果是IsWhiteSpace,请替换为"
  4. 创建所有可能行尾的列表("\ r \ n","\ r","\ n",LF,VT,FF,CR,CR + LF,NEL,LS,PS),然后替换他们用空字符串.很多替换.

我会说最好的结果将是在应用第一种和第四种方法之后,但是我无法确定哪种方法会更快.您认为哪一个是最完整的?

I would say that the best results will be after applying 1st and 4th approaches but I cannot decide which will be faster. Which one do you think is the most complete one?

EDIT#2

我在下面发布了答案.

推荐答案

下面是解决我的问题的扩展方法.当然,可以将LineSeparator和ParagraphEnding定义为静态值等.

Below is the extension method solving my problem. LineSeparator and ParagraphEnding can be of course defined somewhere else, as static values etc.

public static string RemoveLineEndings(this string value)
{
    if(String.IsNullOrEmpty(value))
    {
        return value;
    }
    string lineSeparator = ((char) 0x2028).ToString();
    string paragraphSeparator = ((char)0x2029).ToString();

    return value.Replace("\r\n", string.Empty)
                .Replace("\n", string.Empty)
                .Replace("\r", string.Empty)
                .Replace(lineSeparator, string.Empty)
                .Replace(paragraphSeparator, string.Empty);
}

这篇关于如何消除字符串中的所有换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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