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

Counting lines in a string

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
17 Jan 2012CPOL 9.5K   7
Again, going with other people's comments about memory, how about using a Streamreader? (I haven't tested the timings (or code) but from memory..This should be fast (and memory efficient)...at least in my experience.StreamReader sr = new StreamReader("Put file here");Int32 cnt =...

Again, going with other people's comments about memory, how about using a Streamreader? (I haven't tested the timings (or code) but from memory..


This should be fast (and memory efficient)...at least in my experience.


C#
StreamReader sr = new StreamReader("Put file here");
Int32 cnt = 0;

while (sr.ReadLine() != null)
{
    cnt++;
}

License

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



Comments and Discussions

 
GeneralRe: Damn! :-) Thanks for trying it! Pin
Jon Bellamy18-Jan-12 12:32
Jon Bellamy18-Jan-12 12:32 
GeneralRe: :doh: I forgot you could rewind the underlying stream! :O Mi... Pin
OriginalGriff17-Jan-12 9:33
mveOriginalGriff17-Jan-12 9:33 
GeneralAddendum: Removing the Dispose brought the time down by 10 m... Pin
OriginalGriff17-Jan-12 8:08
mveOriginalGriff17-Jan-12 8:08 
GeneralRe: Thanks for trying, could you at least humour the following t... Pin
Jon Bellamy17-Jan-12 9:04
Jon Bellamy17-Jan-12 9:04 
GeneralNot only is this about strings rather than files, but it is ... Pin
OriginalGriff17-Jan-12 8:07
mveOriginalGriff17-Jan-12 8:07 
General@Jon - Your code is for counting lines in a FILE. This artic... Pin
tmbgfan17-Jan-12 6:05
tmbgfan17-Jan-12 6:05 
GeneralRe: Thank you for pointing that out - with capitals. Whilst I u... Pin
Jon Bellamy17-Jan-12 6:25
Jon Bellamy17-Jan-12 6:25 

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.