【问题标题】:Creating substrings from text file从文本文件创建子字符串
【发布时间】:2012-07-03 19:00:51
【问题描述】:

我有一个包含两行数字的文本文件,我要做的就是将每一行变成一个字符串,然后将它添加到一个数组中(称为字段)。尝试查找 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。

谢谢。

【问题讨论】:

    标签: objective-c string eof


    【解决方案1】:

    你可以使用componentsSeparatedByCharactersInSet:来得到你想要的效果:

    -(NSArray*)parseString:(NSString *)inputString {
        return [inputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    }
    

    【讨论】:

      【解决方案2】:

      简短的回答是使用 [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”的文件,它是纯文本文件。

      【讨论】:

        猜你喜欢
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 2014-08-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 2012-05-26
        相关资源
        最近更新 更多