Re: how does one split a block of newline-separated text into an NSArray of NSStrings?
Re: how does one split a block of newline-separated text into an NSArray of NSStrings?
- Subject: Re: how does one split a block of newline-separated text into an NSArray of NSStrings?
- From: Douglas Davidson <email@hidden>
- Date: Mon, 30 Oct 2006 18:13:49 -0800
On Oct 30, 2006, at 7:32 AM, Stephen Deken wrote:
NSArray *arr = [myString componentsSeparatedByString:@"\n"];
This indeed does exactly what was requested, and would be appropriate
if you know that the interline separator for the text in question
will always be \n.
In more general cases, however, one can use methods that take into
account the variety of possible line terminations that one might
encounter (\n, \r, \r\n, Unicode separators), such as
lineRangeForRange: or getLineStart:end:contentsEnd:forRange:.
For example, one could create a line array with something like this
(untested):
NSArray *lineArrayForString(NSString *string) {
unsigned length = [string length], lineStart = 0, lineEnd = 0,
contentsEnd = 0;
NSMutableArray *array = [NSMutableArray array];
while (lineEnd < length) {
[string getLineStart:&lineStart end:&lineEnd
contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
[array addObject:[string substringWithRange:NSMakeRange
(lineStart, contentsEnd - lineStart)]];
}
return array;
}
This doesn't have precisely the same behavior as
componentsSeparatedByString: for strings ending in a final \n, but
that shouldn't be difficult to change if desired.
Douglas Davidson
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden