Count how many lines a string has

How do I know how many lines a string has. Eg the string is:

" first line

second line

third line"

How do I get three?

Thanks!

Every new line is identified using `\n`. You could split the string on that character and check the count of the result.

No because my string with multiple lines comes from a text view so there are no \n. How do I do this? Thanks.

The following is probably the worst way possible and has nothing to do with Swift. (Caveat programmeur.) Use Core Text with whatever line break scheme for fragments (words, characters, etc) and then base your count on the internal rendering.

Really please just help anyone.

Accepted Answer

Monyschuk,

The code samples you referenced work fine for smaller documents. But, if the document is large, say 10K to 20K lines, it becomes a beach ball bonanza. 🙂

Count how many lines a string has
 
 
Q