Skip navigation.
 
mlRe: Slice a .txt file in lines
FROM : Douglas Davidson
DATE : Tue Jun 20 17:48:57 2006

On Jun 20, 2006, at 8:13 AM, Sean Murphy wrote:

> Here's yet another line-ending-independent way I've been using to 
> split an NSString of lines into an NSArray.  I just thought I'd 
> share it in addition to the previous methods given..
>
> Assumptions..
> NSString *textFileAsString (entire text file in one large string)
> NSArray *linesInTextFile (each line as an array element)
>
> // Finds the first character past the line terminator and the first 
> character of the line terminator, respectively
> unsigned int endOfLineIndex, startOfLineTerminatorIndex;
>
> // Determine key locations of the first line in the file:
> [textFileAsString getLineStart:NULL end:&endOfLineIndex 
> contentsEnd:&startOfLineTerminatorIndex forRange:NSMakeRange(0,0)];
> // (Passing NULL will skip computation for any unneeded values)
> // (Takes the entire line in which the range is found, thus passing 
> the above range picks out the first line)
>
> // Finds the line ending ending character:
> NSString *lineEndCharacter = [textFileAsString 
> substringWithRange:NSMakeRange(startOfLineTerminatorIndex, 
> endOfLineIndex-startOfLineTerminatorIndex)];
>
> // Use the line ending character to split the access log into an 
> array containing each line as a string object
> NSArray *linesInTextFile = [textFileAsString 
> componentsSeparatedByString:lineEndCharacter];
>


This code assumes that the file uses a single line terminator 
consistently throughout.  Andreas' method will use whatever 
terminators occur in the file.

One other note is that there are two sets of methods:  one that uses 
the word "line", and another that uses the word "paragraph".  The 
distinction is because there are line separators that are not 
paragraph separators, U+0085 NEXT LINE and U+2028 LINE SEPARATOR. 
This distinction may or may not be important depending on what you 
are trying to do.

Douglas Davidson

Related mailsAuthorDate
mlSlice a .txt file in lines Neto Jun 20, 07:44
mlRe: Slice a .txt file in lines Ben Lachman Jun 20, 08:11
mlRe: Slice a .txt file in lines Andreas Mayer Jun 20, 14:38
mlRe: Slice a .txt file in lines Sean Murphy Jun 20, 17:13
mlRe: Slice a .txt file in lines Andreas Mayer Jun 20, 17:44
mlRe: Slice a .txt file in lines Douglas Davidson Jun 20, 17:48
mlRe: Slice a .txt file in lines Sean Murphy Jun 20, 19:44
mlRe: Slice a .txt file in lines Neto Jun 21, 05:59