65.9K
CodeProject is changing. Read more.
Home

Counting lines in a string

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 17, 2012

CPOL
viewsIcon

8523

Hello! Great tip!What do you think about this extension method:public static class StringExtension{ public unsafe static long LineCount(this string s) { long lineCount = 1; fixed (char* pchar = s) { char* p = pchar; for (; *p...

Hello! Great tip!

What do you think about this extension method:

public static class StringExtension
{
    public unsafe static long LineCount(this string s)
    {
        long lineCount = 1;
        fixed (char* pchar = s)
        {
            char* p = pchar;
            for (; *p != '\0'; p++)
            {
                if (*p == '\n') lineCount++;
            }
        }
        return lineCount;
    }
}

The class must be compiled into assembly with '/unsafe' option (simply mark "Allow unsafe code" checkbox on "Build" page of properties of project for this assembly).

Usage:

long l = "hello\nmy friend\nGood luck".LineCount();

Please try to test it.