Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 拆分NSString并保留拆分字符_Ios_Objective C_Split_Nsstring - Fatal编程技术网

Ios 拆分NSString并保留拆分字符

Ios 拆分NSString并保留拆分字符,ios,objective-c,split,nsstring,Ios,Objective C,Split,Nsstring,我有一个字符串,其中有一些新行字符,我需要将其拆分。目前我正在使用: NSArray *a = [string componentsSeperatedByString:@"\n"]; 但是,这将删除所有新行字符。如何将这些元素保留为数组的一部分?据我所知,没有API可以执行此操作。一个简单的解决方案是从组件开始构建第二个数组,如下所示 NSString *separator = @"."; NSArray *components = [@"ab.c.d.ef.gh" componentsSep

我有一个字符串,其中有一些新行字符,我需要将其拆分。目前我正在使用:

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

但是,这将删除所有新行字符。如何将这些元素保留为数组的一部分?

据我所知,没有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"] 
NSString*分隔符=@”;
NSArray*组件=[@“ab.c.d.ef.gh”组件由字符串:分隔符分隔];
NSMutableArray*finalComponents=[NSMutableArray阵列容量:components.count*2-1];
[组件enumerateObjectsUsingBlock:^(id组件,整数idx,布尔*停止){
[最终组件添加对象:组件];
if(idx[“ab”,“c”,“d”,“ef”,“gh”]

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

自己拆分字符串

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);

假设你正在处理一个完整的word文档(几页)。这会成为一个问题吗?最简单的答案是:试试看。然而,rmaddy的解决方案可能更有效。这是有效的。我想我还需要一些其他格式化的东西来修复代码中的其他地方。谢谢