Click here to Skip to main content
11,705,764 members (51,835 online)
Click here to Skip to main content

Tagged as

Counting lines in a string

, 17 Jan 2012 CPOL 2.6K
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

You may also be interested in...

Comments and Discussions

 
General.NET strings can have '\0' in the middle, not just at the en... Pin
Qwertie23-Jan-12 20:52
memberQwertie23-Jan-12 20:52 
GeneralFixing an object in place doesn't necessarily yield faster a... Pin
PIEBALDconsult18-Jan-12 2:26
memberPIEBALDconsult18-Jan-12 2:26 
GeneralI had though of using unsafe code, but I didn't get round to... Pin
OriginalGriff17-Jan-12 9:10
mvpOriginalGriff17-Jan-12 9:10 
GeneralRe: Ok, all is clear. Thank you for comparison. Pin
Roman Shero17-Jan-12 9:36
memberRoman 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 | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 17 Jan 2012
Article Copyright 2012 by Roman Shero
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid