我有一個文本文件,其中包含兩行數字,我想要做的就是將每行轉換爲一個字符串,然後將其添加到數組(稱爲字段)。我試圖找到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。
謝謝。