在 Objective-C 中的最后一项之前创建一个逗号分隔列表 "and",特别是

Create a comma-separated list with "and" before the last item in Objective-C, in particular

我想编写一种方法,提供人类可读的数组字符串表示形式,必要时使用逗号-spaces(包括牛津逗号),并在末尾连接“和” .

例如,假设我有这些数组:

NSArray *nun = @[];
NSArray *won = @[@"The Loneliest"];
NSArray *too = @[@"Peas", @"Pod"];
NSArray *tree = @[@"Apple", @"Falls", @"Far, Far Away"];

我想写一个这样的方法:

+ (NSString*) humanReadableListFromArray: (NSArray*) arr
{
  // magic
}

当我传递数组时,我希望它们看起来像这样:

@""
@"The Loneliest"
@"Peas and Pod"
@"Apple, Falls, and Far, Far Away"

请注意,第一个 正好有 1 个项目,只是没有装饰的第一个项目。第二个 恰好有 2 个项目 ,没有逗号,但有连词 " 和 "。第三个 超过 2 个项目,在每个项目之间包含一个逗号-space,最后一个项目在逗号-[ 之后包含一个额外的 and =44=] 和项目之前。

在 Objective C 中有没有捷径可以做到这一点? 我用 Java 这样的语言做到了这一点,但我知道 Objective C 具有类似 -(NSString*)[NSArray componentsJoinedByString:] 的方法,可能有助于此。


这个问题没有被 Replace last comma in string with an "and". (Objective-C) because it does not address commas in the last array item. I've also looked into questions like Objective-C Simplest way to create comma separated string from an array of objects 回答,他们也没有提到人类可读性的这个很好的部分。

TTTFormatterKit 正是您所需要的。

这是项目自述文件中的示例...

NSArray *list = [NSArray arrayWithObjects:@"Russel", @"Spinoza", @"Rawls", nil];
TTTArrayFormatter *arrayFormatter = [[TTTArrayFormatter alloc] init];
[arrayFormatter setUsesSerialDelimiter:NO]; // Omit Oxford Comma
NSLog(@"%@", [arrayFormatter stringFromArray:list]); // "Russell, Spinoza and Rawls"

@timgcarlson 提到的第三方库听起来很有希望。这是我本机要做的...

- (NSString *)humanReadableListFromArray:(NSArray *)array withOxfordStyle:(BOOL)oxford {
    if (array.count == 0) return @"";
    if (array.count == 1) return array[0];
    if (array.count == 2) return [array componentsJoinedByString:@" and "];

    NSArray *firstItems = [array subarrayWithRange:NSMakeRange(0, array.count-1)];
    NSString *lastItem = [array lastObject];
    NSString *lastDelimiter = (oxford)? @", and " : @" and ";
    return [NSString stringWithFormat:@"%@%@%@",
        [firstItems componentsJoinedByString:@", "], lastDelimiter, lastItem];
}

未测试:

+ (NSString*)humanReadableListFromArray:(NSArray*) arr
{
   NSUInteger count = [arr count];
   if (count == 0)
        return @"";
   else if (count == 1)
        return arr[0];

   NSString *subarrayStr;
   if (count == 2) {
       subarrayStr = arr[0];
   } else {
       NSArray *subarray = [arr subarrayWithRange:NSMakeRange(0, count - 1)];
       subarrayStr = [subarray componentsJoinedByString:@", "];
   }

   return [[subarrayStr stringByAppendingString:@" and "] stringByAppendingString:arr[count - 1]];
}

Swift3 中的操作方法如下:

extension Collection where Iterator.Element == String {
    func joinedWithComma() -> String {
        var string = joined(separator: ", ")

        if let lastCommaRange = string.range(of: ", ", options: .backwards) {
            string.replaceSubrange(lastCommaRange, with: " and ")
        }

        return string
    }
}

["A", "B", "C"].joinedWithComma() // returns "A, B and C"

这里是 Swift 4 版本。它支持项目内的逗号、牛津逗号的可选使用和最大项目数。如果元素的数量高于 maxItemCount,它会缩短列表并将等添加到列表的末尾。注意:假设此函数用于将列表添加到句子的末尾,因此 "etc" 之后没有标点符号,否则您将得到 2 个句号,例如"I like many fruits: apples, pears, strawberries, etc.."

extension Array where Iterator.Element == String {
    func joinedWithComma(useOxfordComma: Bool = false, maxItemCount: Int = -1) -> String {
        let result: String
        if maxItemCount >= 0 && count > maxItemCount {
            result = self[0 ..< maxItemCount].joined(separator: ", ") + ", etc"
        } else if count >= 2 {
            let lastIndex = count - 1
            let extraComma = (useOxfordComma && count > 2) ? "," : ""
            result = self[0 ..< lastIndex].joined(separator: ", ") + extraComma + " and " + self[lastIndex]
        } else if count == 1 {
            result = self[0]
        } else {
            result = ""
        }

        return result
    }
}