Click here to Skip to main content
15,880,405 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Counting lines in a string

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Jan 2012CPOL 7.6K   4
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:


C#
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:


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

Please try to test it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
General.NET strings can have '\0' in the middle, not just at the en... Pin
Qwertie23-Jan-12 20:52
Qwertie23-Jan-12 20:52 
GeneralFixing an object in place doesn't necessarily yield faster a... Pin
PIEBALDconsult18-Jan-12 2:26
mvePIEBALDconsult18-Jan-12 2:26 
GeneralI had though of using unsafe code, but I didn't get round to... Pin
OriginalGriff17-Jan-12 9:10
mveOriginalGriff17-Jan-12 9:10 
GeneralRe: Ok, all is clear. Thank you for comparison. Pin
Roman Shero17-Jan-12 9:36
Roman Shero17-Jan-12 9:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.