【发布时间】:2014-08-12 20:20:10
【问题描述】:
假设我有一个包含列表的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];
}
【问题讨论】:
-
您最好使用正则表达式拆分字符串:stackoverflow.com/q/18799566/535275。
-
如果这是唯一的拆分形式:">,"。循环并添加回“>”。
-
@Zaph,这只是一个例子。我正在寻找所述问题的通用解决方案,而不是示例的具体答案。