【发布时间】:2015-09-03 08:35:35
【问题描述】:
我试图从文件中读取的文本如下所示:“DREAM_TITLE: blah blah blah”。我遇到的问题是在 for 循环中(特别是 containsString 方法),它一直告诉我关键 DREAM_TITLE 不存在,当它明显存在并且它甚至被加载到初始数组中时。请停下来!这里很菜鸟,如果有人冒犯了,对不起。谢谢!
-(NSMutableArray *)findValueForKey:(NSString *)key{
NSString *path = [[NSBundle mainBundle] pathForResource:@"sampleData"
ofType:@"txt"];
NSString *fileContent = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableArray *arrayOfKeyValues = [[NSMutableArray alloc] init];
NSArray *numberOfLines = [[NSArray alloc] initWithObjects:[fileContent componentsSeparatedByString:@"\n"], nil];
for (int i=0; i<[numberOfLines count]; i++){
if ([[numberOfLines objectAtIndex:i] containsObject:key]){
NSArray *tempArray = [numberOfLines[i] componentsSeparatedByString:@":"];
[arrayOfKeyValues insertObject:[tempArray objectAtIndex:1] atIndex:i];
}
else {
[arrayOfKeyValues insertObject:@"no value for key found" atIndex:i];
}
}
return arrayOfKeyValues;
【问题讨论】:
-
你试过这个吗? NSArray *numberOfLines = [fileContent componentsSeparatedByString:@"\n"];注意: componentsSeparatedByString 返回 NSArray
-
如果上述方法不能解决您的问题,请提供文本文件的内容/文本文件的示例内容。
-
问题解决了,我一直在搞乱它,在这里和那里进行调整,终于成功了!甚至让被爆破的 containsString 以应有的方式工作。
标签: objective-c string-parsing