• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: how does one split a block of newline-separated text into an NSArray of NSStrings?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


References: 
 >how does one split a block of newline-separated text into an NSArray of NSStrings? (From: mercer <email@hidden>)
 >Re: how does one split a block of newline-separated text into an NSArray of NSStrings? (From: "Stephen Deken" <email@hidden>)

  • Prev by Date: NSTableView Columns live resizing during Window Resize
  • Next by Date: Re: Re: Scrolling text in Status Item - adding a menu
  • Previous by thread: Re: Re: how does one split a block of newline-separated text into an NSArray of NSStrings?
  • Next by thread: Re: how does one split a block of newline-separated text into an NSArray of NSStrings?
  • Index(es):
    • Date
    • Thread