Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Counting lines in a string

, 17 Jan 2012
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

Roman Shero

Russian Federation Russian Federation
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 17 Jan 2012
Article Copyright 2012 by Roman Shero
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid