读取文本文件的特定部分 [英] Reading Specific Part Of A Text File

查看:55
本文介绍了读取文本文件的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些与此类似的问题,但与XCode无关.

I've found a few similar questions to this but not relating to XCode.

我正在创建一个应用,其中单击按钮会生成随机报价,并将其显示在标签中.

I am creating an app where clicking a button generates a randomised quote and displays it in a label.

我想做的是创建一个带有所有引号的文本文件,然后让我的应用从该文件中随机选择一个引号.

What I'd like to do is have a text file with all of the quotes, then have my app randomly select a quote from that file.

问题是我目前的代码读取了文件的全部内容.

The problem is that my code at present reads the entire contents of the file.

    textHIYP = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
textHIYP.editable = NO;
[self.view addSubview:textHIYP];

textHIYP.text = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Quotes" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];

我能想到的唯一的另一种方法是拥有一个arc4random()代码,该代码随机化它所在的文件,每个文件都包含一个单引号...但是我希望有一百多个引号,似乎不理想.

The only other way I can think of doing it is to have an arc4random() code that randomises which file it locates, with each file containing a single quote...but as I want to have over a hundred quotes, this seems less than ideal.

关于如何阅读文本文件的特定行的任何建议?

Any suggestions as to how to read a particular line of a text file?

先感谢堆!

推荐答案

您可以将整个文件读取为 NSString ,然后使用 componentsSeparatedByString:@"\ n将其拆分为一个数组",保留它的内存,并在需要时返回该数组的随机元素.如果只有几百行(而不是几百万行),那么使用额外的内存就不会成为问题.

You could read the whole file into an NSString, then split it into an array with componentsSeparatedByString:@"\n", keep that it memory, and return a random element of the array when needed. If there are just hundreds (and not, say, millions) of lines, the additional memory used should not be an issue.

这篇关于读取文本文件的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆