假设我有一个包含列表的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];
}发布于 2014-08-12 21:59:17
你应该看看的不是NSString,而是NSScanner。创建一个NSScanner,它将以您想要的方式解析NSString。如果您知道某些字符永远不会出现,则可以将引号之间的逗号更改为其中一个字符,然后将字符串分解为数组,然后用逗号替换临时字符。您可能会创建一个NSScanner,如果您真正进入它,它将执行所有的解析工作。
https://stackoverflow.com/questions/25273394
复制相似问题