开发者

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. I assume this would equate to "开发者_Go百科\r\n" or Environment.NewLine in C#. However , when I perform a comparison like this it always seem to return 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 (i.e. "").


Are you sure that the whole string only contains a NewLine and nothing more or less? Have you already tried str.Contains(Environment.NewLine)?


The most obvious troubleshooting step would be to check what the value of str actually is. Just view it in the debugger or print it out.


Newline is "\r\n", not "/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


This is a very valid question.

Here is the answer. I have invented a kludge that takes care of it.

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
  ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜