拆分NSString并保持拆分字符

时间:2013-11-07 21:53:35

标签: ios objective-c split nsstring

我有一个包含一些新行字符的字符串,我需要拆分它。目前我正在使用:

NSArray *a = [string componentsSeperatedByString:@"\n"];

然而,这摆脱了所有新行字符。如何将这些元素保留为数组的一部分?

2 个答案:

答案 0 :(得分:0)

据我所知,没有API可以做到这一点。一个简单的解决方案是从组件开始构建第二个数组,如下所示

NSString *separator = @".";
NSArray *components = [@"ab.c.d.ef.gh" componentsSeparatedByString:separator];
NSMutableArray *finalComponents = [NSMutableArray arrayWithCapacity:components.count * 2 - 1];
[components enumerateObjectsUsingBlock:^(id component, NSUInteger idx, BOOL *stop) {
    [finalComponents addObject:component];
    if (idx < components.count - 1) {
        [finalComponents addObject:separator];
    }
}];
NSLog(@"%@", finalComponents); // => ["ab", ".", "c", ".", "d", ".", "ef", ".", "gh"] 

效率不高,但除非处理大量组件,否则可能不是一个大问题。

答案 1 :(得分:0)

自己拆分字符串。

NSMutableArray *lines = [NSMutableArray array];
NSRange searchRange = NSMakeRange(0, string.length);
while (1) {
    NSRange newlineRange = [string rangeOfString:@"\n" options:NSLiteralSearch range:searchRange];
    if (newlineRange.location != NSNotFound) {
        NSInteger index = newlineRange.location + newlineRange.length;
        NSString *line = [string substringWithRange:NSMakeRange(searchRange.location, index - searchRange.location)];
        [lines addObject:line];
        searchRange = NSMakeRange(index, string.length - index);
    } else {
        break;
    }
}

NSLog(@"lines = %@", lines);
相关问题