2011-04-05 66 views
0

我有13条文本行,格式如下: “1234 56789 1235 98765 ...”(四位数字 - 空格 - 五位数字)循环三次。 问题是空白区域有时可能不存在。像这样: “1234 56789 123598765 ...”,但分隔4和5位仍然相关。将NSString操作为2D NSMutableArray

我对我如何将每行的内容剪切并粘贴到类似数据结构的表格感到困惑。这是我到目前为止有:

for (int column = 0; column < 6; column++) { 
     // take first 4 digits 
     cursor_offset += 4; 
     temp = [entry substringWithRange:NSMakeRange(cursor,cursor_offset)]; 
     cursor = cursor_offset; // update cursor position 
     if ([entry substringWithRange:NSMakeRange(cursor_offset,cursor_offset+1)] isEqualToString:@" "]) { 
      // space jump 
      cursor_offset+=1; // identify blank space and jump over it 
     } 
在这之后我还去试图抓住另外6位

... 有没有一种更聪明的办法做到这一点?我想到了正则表达式,我宁愿不要着急。任何最佳做法?

回答

1

我可能只是删除所有字符串中的空格,然后大块出片:

NSString *source = @"1234 56789 1234 1234 56789 1234 1234 56789 1234 1234 56789 1234 1234 56789 1234"; 
NSString *stripped = [[source componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet] componentsJoinedByString:@""]; 

NSAssert([stripped length] % 13 == 0, @"string length must be a multiple of 13"); 

NSMutableArray *sections = [NSMutableArray array]; 
for (NSInteger location = 0; location < [stripped length]; location += 13) { 
    NSString *substring = [stripped substringWithRange:NSMakeRange(location, 13)]; 
    NSArray *fields = [NSArray arrayWithObjects: 
        [substring substringWithRange:NSMakeRange(0,4)], 
        [substring substringWithRange:NSMakeRange(4,5)], 
        [substring substringWithRange:NSMakeRange(9,4)], 
        nil]; 
    [sections addObject:fields]; 
} 

警告在浏览器中输入的,而不是编译。 Caveat Implementor

+0

优雅。这比我进行的笨拙的for-loop要聪明得多...谢谢 – 2011-04-06 17:55:46

相关问题