假设我有一个包含列表的NSString
对象。列表中包含一些引号,其中包含分隔符。如何最好将其拆分为数组?
一个例子是名称和电子邮件地址列表,以逗号分隔:
"Bar, Foo" <foo@bar.com>, "Blow, Joe" <joe@Blow.com>
我找到了一个解决方案,但我想知道是否有更高效的解决方案。我的解决方案基本上是这样的:
-componentsSeparatedByString
将新字符串解析为数组。似乎应该有NSString
方法执行此操作,但我找不到。
对于它的价值,这是我的解决方案:
-(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];
}
答案 0 :(得分:0)
你应该关注的不是NSString,而是NSScanner。创建一个NSScanner,它将以您希望的方式解析NSString。如果您知道某些字符永远不会出现,您可以在引号之间更改逗号,然后将字符串分解为数组,然后用逗号替换临时字符。您可以创建一个NSScanner,如果您真的进入它,它将执行所有解析。