2014-10-29 65 views
3

我有以下字符串。从C#中删除新行字符字符串

string str = @"One 
Two 

Four 
Five 
Six 
Seven 
Eight 




Thirteen 






Twenty 


"; 

我想删除此字符串中多余的新行。所以该字符串应该看起来像:

str = "One 
Two 
Four 
Five 
Six 
Seven 
Eight 
Thirteen 
Twenty" 

我正在使用此代码,但它不起作用。

Str = Str.Replace("\n\n", "\n"); 
      while (Str.IndexOf("\n") > 0) 
      { 
       Str = Str.Replace("\n\n", "\n"); 
      } 

我甚至尝试过Str = Str.Replace("\u000a\u000a", "\u000a");但仍然没有解决。

+0

我现在还不确定,是第一个参数regex?如果是的话,这应该工作'Str.Replace(“[\ n] +”,“\ n”);'或者可能包括空格:'Str.Replace(“[] * [\ n] + [] *” ,“\ n”);' – libik 2014-10-29 16:16:49

回答

7

您可以将字符串分割成线,取出空项,并加入其重新组合:

var lines = str.Split('\n') 
       .Where(s => !string.IsNullOrWhiteSpace(s)); 

str = string.Join("\n", lines); 
+2

+1,但使用'string.IsNullOrWhiteSpace()'而不是'string.IsNullOrEmpty(s.Trim())' – Habib 2014-10-29 16:29:44

+0

@Habib很好的调用! – DavidG 2014-10-29 16:32:57

+0

@DavidG:您的代码无法正常工作。我遇到错误: 1.'string.Join(string,string [])'的最佳重载方法匹配有一些无效参数。 2.参数2:无法从'System.Collections.Generic.IEnumerable '转换为'string []'。 – Kamran 2014-10-29 17:25:57

3

试试这个:

str = System.Text.RegularExpressions.Regex.Replace(str, "(" + Environment.NewLine + ")+", Environment.NewLine) 

here更多地了解Environment.Newline。但是,即使上面的代码不保证删除重复的换行,因为你在解析文档或字符串可以在不同的机器上创建其中一个新行的代码是diferent:

  • "\r\n" - 窗口换行,
  • "\n" - UNIX换行符,
  • "\r“ - MAC换行符

为了引入到正则表达式,wikipedia文章应该是相当翔实的,但一般:

  • Environment.Newline可以是多种字符,如"\r\n"并且所以我在"()"包围此变量将其标记为一个基团,其应被视为原子字符(单个元件)的,
  • "+"相匹配的前一个元素(Environment.Newline,包含在"()"中)一次或多次。

感谢以上和Regex.Replace我们得到了正确的输出。

+2

问题在于它没有处理3个或更多换行符。 – DavidG 2014-10-29 16:17:55

+0

@DavidG更新了答案。 – 2014-10-29 16:33:24

+0

更好,但也许是对外行的正则表达式的解释? – DavidG 2014-10-29 16:34:32

0

我想你的代码,并将其挂在一段时间。由于替换将永远不会摆脱所有的\n实例,这是可以预料的。你想你目前的改变而循环到这一点:

while (str.IndexOf("\n\n") > 0) 
{ 
    str = str.Replace("\n\n", "\n"); 
} 

这将循环,直到\n\n任何重复实例已被删除。

编辑:我测试过这个和各种案例,只要字符串不以\n\n\n开头,它就会起作用。