2

我有一个包含两行数字的文本文件,我要做的就是将每一行变成一个字符串,然后将它添加到一个数组(称为字段)中。尝试查找 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。

谢谢。

4

2 回答 2

0

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

-(NSArray*)parseString:(NSString *)inputString {
    return [inputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}
于 2012-07-03T19:06:30.007 回答
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”的文件,它是纯文本文件。

于 2012-07-03T19:14:49.913 回答