1

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];

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I never knew that. Nice! +1
This is good, but it will interpret CRLF as two different line endings, so you'll be left with an empty element in the array for each CRLF.
3

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...
}

3 Comments

If it's a line feed/carriage return, you can try componentsSeparatedByString:@"\n"
'componentSeparatedByCharactersInSet' actually created an index with the '\r\n'. So I replaced it with the following change:
NSArray *lines = [response componentsSeparatedByString:@"\r\n"];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.