-4

我有一个来自这种格式的文件的值列表:

#number of items#
#item type#value x#value y#
#...

例子:

#100#
#1#150#200#
#1#250#200#
#2#350#200#
#2#450#250#
#1#550#350#
#...

想将其读入代码中...

4

1 回答 1

1

You can do something like this, don't know about performance though

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

NSArray *lines = [fileContent componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

if (lines.count > 1)
{
    NSString *firstLine = [lines objectAtIndex:0];
    NSCharacterSet *seperatorSet = [NSCharacterSet characterSetWithCharactersInString:@"#"];

    int itemCount = [[firstLine stringByTrimmingCharactersInSet:seperatorSet] intValue];

    for (int i = 1; i < lines.count; ++i)
    {
        NSString *line = [lines objectAtIndex:i];
        NSArray  *components = [line componentsSeparatedByCharactersInSet:seperatorSet];

        //starts at 1 because first and last are empty strings
        int type = [[components objectAtIndex:1] intValue];
        int x    = [[components objectAtIndex:2] intValue];
        int y    = [[components objectAtIndex:3] intValue];
    }
}
于 2012-07-20T15:26:37.110 回答