简体   繁体   English

确定字符串是否为 C# 中的换行符

[英]Determine if string is newline in C#

I am somehow unable to determine whether a string is newline or not.我不知何故无法确定一个字符串是否是换行符。 The string which I use is read from a file written by Ultraedit using DOS Terminators CR/LF.我使用的字符串是从 Ultraedit 使用 DOS Terminators CR/LF 编写的文件中读取的。 I assume this would equate to "\\r\\n" or Environment.NewLine in C#.我认为这等同于 C# 中的 "\\r\\n" 或 Environment.NewLine。 However , when I perform a comparison like this it always seem to return false :但是,当我执行这样的比较时,它似乎总是返回 false:

if(str==Environment.NewLine)

Anyone with a clue on what's going on here?有人知道这里发生了什么吗?

How are the lines read?行是怎么读的? If you're using StreamReader.ReadLine (or something similar), the new line character will not appear in the resulting string - it will be String.Empty or (ie "").如果您使用的是 StreamReader.ReadLine(或类似的东西),换行符将不会出现在结果字符串中——它将是 String.Empty 或(即“”)。

Are you sure that the whole string only contains a NewLine and nothing more or less?您确定整个字符串只包含一个 NewLine 而不是更多或更少吗? Have you already tried str.Contains(Environment.NewLine) ?您是否已经尝试过str.Contains(Environment.NewLine)

The most obvious troubleshooting step would be to check what the value of str actually is.最明显的故障排除步骤是检查str实际值。 Just view it in the debugger or print it out.只需在调试器中查看或打印出来。

Newline is "\\r\\n", not "/r/n".换行符是“\\r\\n”,而不是“/r/n”。 Maybe there's more than just the newline.... what is the string value in Debug Mode?也许不仅仅是换行符......调试模式下的字符串值是什么?

You could use the new .NET 4.0 Method: String.IsNullOrWhiteSpace您可以使用新的 .NET 4.0 方法:String.IsNullOrWhiteSpace

This is a very valid question.这是一个非常有效的问题。

Here is the answer.这是答案。 I have invented a kludge that takes care of it.我发明了一个kludge来照顾它。

static bool StringIsNewLine(string s)
{
    return (!string.IsNullOrEmpty(s)) &&
        (!string.IsNullOrWhiteSpace(s)) &&
        (((s.Length == 1) && (s[0] == 8203)) || 
        ((s.Length == 2) && (s[0] == 8203) && (s[1] == 8203)));
}

Use it like so:像这样使用它:

foreach (var line in linesOfMyFile)
{
  if (StringIsNewLine(line)
  {
    // Ignore reading new lines
    continue;
  }

  // Do the stuff only for non-empty lines
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM