【问题标题】:Manipulate NSString to 2D NSMutableArray将 NSString 操作为 2D NSMutableArray
【发布时间】:2011-04-05 19:38:28
【问题描述】:

我有 13 个文本行,格式如下: “1234 56789 1235 98765 ...”(四位数 - 空格 - 五位数)循环 3 次。 问题是空白空间有时可能不存在。像这样: "1234 56789 123598765 ..." 但 4 位和 5 位数字的分隔仍然相关。

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

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 个数字... 有没有更聪明的方法来做到这一点?我想到了我不想麻烦的正则表达式。有什么最佳做法吗?

【问题讨论】:

    标签: iphone objective-c xcode nsstring nsarray


    【解决方案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];
    }
    

    警告,在浏览器中输入但未编译。 警告实施者

    【讨论】:

    • 优雅。这比我进行的笨拙的 for 循环要聪明得多...谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    相关资源
    最近更新 更多