View Full Version : NSString & lines.
Jan 14, 2005, 11:46 AM
Hi again guys,
I'm looking for a way to either iterate over each line in an NSString or to to count the number of lines in an NSString so that I can iterate over them ;). If anyone could point me in the right direction it would be much appreciated!
Also, is there a way to strip unwanted characters from the start/end of a line: like chomp in perl or strip() in Python.
Thanks in advance,
Jan 14, 2005, 12:02 PM
Take a look at the NSString documentation on XCode. The - (NSArray *)componentsSeparatedByString:(NSString *)separator looks promising (@"\n" would be the separator)
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set can be used like chomp.
Jan 14, 2005, 12:35 PM
Thanks Robbie, the stringByTrimmingCharactersInSet: method was just what I was looking for :).
I'm not so sure about the line separation because the approach doesn't seem unicode compatible (I could be wrong).
From the docs on "getLineStart:end:contentsEnd:forRange:"
A line is delimited by any of these characters, the longest possible sequence being preferred to any shorter:
U+000D (\r or CR)
U+2028 (Unicode line separator)
U+000A (\n or LF)
U+2029 (Unicode paragraph separator)
\r\n, in that order (also known as CRLF)
Maybe someone could answer this: in a unicode string, is the line terminator still "\n" or some other character? The string I'm working with is from an NSTextView if that helps.
Thanks again :),
Jan 14, 2005, 12:50 PM
Seems to be a fair point. Create some sort of recursive method to loop over separating by each possible line end character in turn?
Jan 14, 2005, 02:40 PM
I wrote a C library to do something like that, available at
It's a bit stubby right now, but it will eventually have a VCount method. I haven't worked on it for a bit, though :P