c# - How to get the line count in a string using .NET (with any line break) -
i need count number of lines in string. line break can character can present in string (cr, lf or crlf).
so possible new line chars: * \n * \r * \r\n
for example, following input:
this [\n] string [\r] has 4 [\r\n] lines
the method should return 4 lines. know built in function, or implemented it?
static int getlinecount(string input) { // provide implementation method? // want avoid string.split since performs bad }
note: performance important me, because read large strings.
thanks in advance.
int count = 0; int len = input.length; for(int = 0; != len; ++i) switch(input[i]) { case '\r': ++count; if (i + 1 != len && input[i + 1] == '\n') ++i; break; case '\n': // uncomment below include other line break sequences // case '\u000a': // case '\v': // case '\f': // case '\u0085': // case '\u2028': // case '\u2029': ++count; break; }
simply scan through, counting line-breaks, , in case of \r
test if next character \n
, skip if is.
performance important me, because read large strings.
if @ possible then, avoid reading large strings @ all. e.g. if come streams pretty easy directly on stream there no more one-character read-ahead ever needed.
here's variant doesn't count newlines @ end of string:
int count = 1; int len = input.length - 1; for(int = 0; < len; ++i) switch(input[i]) { case '\r': if (input[i + 1] == '\n') { if (++i >= len) { break; } } goto case '\n'; case '\n': // uncomment below include other line break sequences // case '\u000a': // case '\v': // case '\f': // case '\u0085': // case '\u2028': // case '\u2029': ++count; break; }
this therefore considers ""
, "a line"
, "a line\n"
, "a line\r\n"
each 1 line only, , on.
Comments
Post a Comment