【问题标题】:Parsing text file with Objective C (issues with containsString:)使用 Objective C 解析文本文件(包含字符串的问题:)
【发布时间】: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


【解决方案1】:

当原始数组已经足够时,您出于某种原因创建了一个数组数组:

NSArray *numberOfLines = [[NSArray alloc] initWithObjects:[fileContent  componentsSeparatedByString:@"\n"], nil];

这可以很简单:

NSArray *lines = [fileContent  componentsSeparatedByString:@"\n"];

接下来,要搜索数组中的每一行,只需使用[NSString rangeOfString:]

for (NSUInteger i = 0; i < [lines count]; i++) {
    if ([lines[i] rangeOfString:key].location != NSNotFound) {
        NSArray *tempArray = [lines[i] componentsSeparatedByString:@":"];
        [arrayOfKeyValues addObject:tempArray[1]];
     } else {
        [arrayOfKeyValues addObject:@"no value for key found"];
     }
}

虽然这不是特别准确,因为您应该只在 : 之前的文本中搜索 key...

【讨论】:

  • 感谢您的所有帮助和建议!我已经设法实现了 cmets 的一些调整,并让我的代码正常工作!为 stackOverflow 社区干杯!
猜你喜欢
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多