2012-07-03 43 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”文件,该文件是纯文本文件。