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