Suppose I have an NSString
object that contains a list. Included in the list are some quotes, which contain the separator character. How best to split this up into an array?
An example would be a list of names and email addresses, separated by commas:
"Bar, Foo" <foo@bar.com>, "Blow, Joe" <joe@Blow.com>
I found a solution, but I'm wondering if maybe there's a more efficient solution. My solution was basically this:
-componentsSeparatedByString
. It seems like there should be an NSString
method that does this, but I didn't find one.
For what it's worth, here's my solution:
-(NSArray *)listFromString:(NSString *)originalString havingQuote:(NSString *)quoteChar separatedByDelimiter:(NSString *)delimiter {
// First we need to parse originalString to replace occurrences of the delimiter with tokens.
NSMutableArray *arrayOfQuotes = [[originalString componentsSeparatedByString:quoteChar] mutableCopy];
for (int i=1; i<[arrayOfQuotes count]; i +=2) {
//Replace occurrences of delimiter with a token
NSString *stringToMassage = arrayOfQuotes[i];
stringToMassage = [stringToMassage stringByReplacingOccurrencesOfString:delimiter withString:@"~~token~~"];
arrayOfQuotes[i] = stringToMassage;
}
NSString *massagedString = [[arrayOfQuotes valueForKey:@"description"] componentsJoinedByString:quoteChar];
// Now we have a string with the delimiters replaced by tokens.
// Next we divide the string by the delimeter.
NSMutableArray *massagedArray = [[massagedString componentsSeparatedByString:delimiter] mutableCopy];
// Finally, we replace the tokens with the quoteChar
for (int i=0; i<[massagedArray count]; i++) {
NSString *thisItem = massagedArray[i];
thisItem = [thisItem stringByReplacingOccurrencesOfString:@"~~token~~" withString:delimiter];
massagedArray[i] = thisItem;
}
return [massagedArray copy];
}
It's not NSString you should be looking at, but NSScanner. Create an NSScanner that will parse the NSString the way you want. If you know that certain characters will never occur, you can change commas between quotes to one of those characters, then explode the string into an array, then replace the temporary character with a comma. You can probably create an NSScanner that will do all the parsing if you really get into it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.