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];
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.
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...
}
精彩评论