draion
draion

Reputation: 443

Creating an array from a text file read from a URL

I am reading a text file from a URL and want to parse the contents of the file into an array. Below is a snippet of the code I am using. I want to be able to place each line of the text into the next row of the array. Is there a way to identify the carriage return/line feed during or after the text has been retrieved?

NSURL *url = [NSURL URLWithString:kTextURL];
textView.text = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding                        error:nil];

Upvotes: 1

Views: 1992

Answers (2)

Drew C
Drew C

Reputation: 6458

When separating by newline characters it's best to use the following procedure:

NSCharacterSet *newlines = [NSCharacterSet newlineCharacterSet];
NSArray *lineComponents = [textFile componentsSeparatedByCharactersInSet:newlines];

This ensures that you get lines separated by either CR, CR+LF, or NEL.

Upvotes: 9

Jacob Relkin
Jacob Relkin

Reputation: 163228

You can use NSString's -componentsSeparatedByString: method, which will return to you an NSArray:

NSURL *url = [NSURL URLWithString:kTextURL];
NSString *response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding];
textView.text = response;
NSArray *lines = [response componentsSeparatedByString:@"\n"];

//iterate through the lines...
for(NSString *line in lines) {
   //do something with line...
}

Upvotes: 3

Related Questions