Click here to Skip to main content
15,558,642 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 17 Jan 2012

Tagged as

Stats

7K views

Counting lines in a string

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Jan 2012CPOL
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 21:52
Qwertie23-Jan-12 21:52 
GeneralFixing an object in place doesn't necessarily yield faster a... Pin
PIEBALDconsult18-Jan-12 3:26
professionalPIEBALDconsult18-Jan-12 3:26 
GeneralI had though of using unsafe code, but I didn't get round to... Pin
OriginalGriff17-Jan-12 10:10
mveOriginalGriff17-Jan-12 10:10 
GeneralRe: Ok, all is clear. Thank you for comparison. Pin
Roman Shero17-Jan-12 10:36
Roman Shero17-Jan-12 10: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.