【问题标题】:Splitting a string into an array, where individual items may contain the delimiter将字符串拆分为数组,其中单个项目可能包含分隔符
【发布时间】: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,这只是一个例子。我正在寻找所述问题的通用解决方案,而不是示例的具体答案。

标签: ios nsstring


【解决方案1】:

您应该查看的不是 NSString,而是 NSScanner。创建一个 NSScanner,它将按照您想要的方式解析 NSString。如果您知道某些字符永远不会出现,您可以将引号之间的逗号更改为其中一个字符,然后将字符串分解为一个数组,然后用逗号替换临时字符。如果你真的进入它,你可能可以创建一个 NSScanner 来完成所有的解析。

【讨论】:

  • P.P.S.当然,使用不在字符串中的分隔符(如制表符)会更容易。
  • 这是一个与NSScanner 解决方案基本相似的问题:stackoverflow.com/questions/12903167/… 我将来可能会考虑这样的事情或正则表达式。这些选项似乎都不优雅,但也许没有优雅的解决方案。
  • 我使用过 NSScanner,它实际上非常优雅,因为它可以拾取许多不同的序列并正确处理它们。而且完成的代码比正则表达式更容易阅读(除非你是正则表达式专家,我不是)。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多