从文本文件创建子字符串

时间:2012-07-03 19:00:52

标签: objective-c string eof

我有一个包含两行数字的文本文件,我想要做的就是将每一行转换为一个字符串,然后将其添加到一个数组(称为字段)中。当我试图找到EOF角色时,我的问题就出现了。我可以从文件中读取没有问题:我把它的内容转换为NSString,然后传递给这个方法。

-(void)parseString:(NSString *)inputString{

NSLog(@"[parseString] *inputString: %@", inputString);

//the end of the previous line, this is also the start of the next lien
int endOfPreviousLine = 0;

//count of how many characters we've gone through
int charCount = 0;

//while we havent gone through every character
while(charCount <= [inputString length]){
    NSLog(@"[parseString] while loop count %i", charCount);

    //if its an end of line character or end of file
    if([inputString characterAtIndex:charCount] == '\n' || [inputString characterAtIndex:charCount] == '\0'){

        //add a substring into the array
        [fields addObject:[inputString substringWithRange:NSMakeRange(endOfPreviousLine, charCount)]];
        NSLog(@"[parseString] string added into array: %@", [inputString substringWithRange:NSMakeRange(endOfPreviousLine, charCount)]);

        //set the endOfPreviousLine to the current char count, this is where the next string will start from
        endOfPreviousLine = charCount+1;
    }

    charCount++;

}
NSLog(@"[parseString] exited while.  endOfPrevious: %i, charCount: %i", endOfPreviousLine, charCount);

}

我的文本文件的内容如下所示:

123
456

我可以得到第一个字符串(123)没问题。电话会是:

[fields addObject:[inputString substringWithRange:NSMakeRange(0, 3)]];

接下来,我调用第二个字符串:

[fields addObject:[inputString substringWithRange:NSMakeRange(4, 7)]];

但是我收到错误,我认为这是因为我的索引超出范围。由于索引从0开始,没有索引7(我认为它应该是EOF字符),我收到错误。

总结一下:当只有6个字符+ EOF字符时,我不知道如何处理7的索引。

感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用componentsSeparatedByCharactersInSet:来获得您正在寻找的效果:

-(NSArray*)parseString:(NSString *)inputString {
    return [inputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}

答案 1 :(得分:0)

简短回答是使用[inputString componentsSeparatedByString:@“\ n”]并获取数字数组。

实施例: 使用以下代码获取数组中的行

    NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"aaa" ofType:@"txt"];
NSString *str = [[NSString alloc] initWithContentsOfFile: path];
NSArray *lines = [str componentsSeparatedByString:@"\n"];
NSLog(@"str = %@", str);
NSLog(@"lines = %@", lines);

上面的代码假设您的资源中有一个名为“aaa.txt”的文件,它是纯文本文件。