2012-07-03 74 views
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。

謝謝。

回答

0

您可以使用componentsSeparatedByCharactersInSet:獲得您正在尋找的效果:

-(NSArray*)parseString:(NSString *)inputString { 
    return [inputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 
} 
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」文件,該文件是純文本文件。