How to split Environment.NewLine?

I want to count the number of lines in a text.

Below works fine:

int numLines = copyText.Split('\n').Length - 1;

      

However, I have used System.Environment.NewLine

all over my code and when I try:

 int numLines = copyText.Split(System.Environment.NewLine).Length - 1;

      

It keeps lifting the red curved line under the expression, can't convert the string to char. Tried to fix this but no luck. Does anyone have any idea?

+3


source to share


3 answers


To break on a new line, you can use the following:

copyText.Split(new string[] { System.Environment.NewLine },
               StringSplitOptions.None).Length - 1;

      

Here is a link to an overload that uses a string array.



Note that System.Environment.NewLine is of type System.String

. On Windows, this 2-character string: \r\n

and Unix systems - 1 character string: \n

. This is why you cannot use it like char.

Wikipedia has a good news article: https://en.wikipedia.org/wiki/Newline

I recommend reading it.

+8


source


As @Jesse Good points out, there are several kinds of newlines that can appear on a line. Regular expression can be used to match different types of strings that may appear in a string:

var text = "line 1\rline 2\nline 3\r\nline 4";

/* A regular expression that matches Windows newlines (\r\n),
    Unix/Linux/OS X newlines (\n), and old-style MacOS newlines (\r).
    The regex is processed left-to-right, so the Windows newlines
    are matched first, then the Unix newlines and finally the
    MacOS newlines. */
var newLinesRegex = new Regex(@"\r\n|\n|\r", RegexOptions.Singleline);
var lines = newLinesRegex.Split(text);

Console.WriteLine("Found {0} lines.", lines.Length);

foreach (var line in lines)
  Console.WriteLine(line);

      



Output:

Found 4 lines.
line 1
line 2
line 3
line 4

+5


source


You have to use an overload that takes String[]

:

int numLines = copyText.Split(new[]{System.Environment.NewLine}, StringSplitOptions.None).Length - 1;

      

+2


source







All Articles