Reading Specific Part Of A Text File

2019-09-05 15:39发布

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];

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?

Thanks heaps in advance!

2条回答
我想做一个坏孩纸
2楼-- · 2019-09-05 16:04

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.

查看更多
Emotional °昔
3楼-- · 2019-09-05 16:15

You're imitating the behavior of the old fortune program, so adopt its tactic, too. The database of quotes is a set of files with quotes separated by lines containing only a special character:

Cabbage crates coming over the briny!
%
Top hole, squiffy!
%
Next we have number four, ”crunchy frog“.
%
Lemon curry?
%

For each of those quote files, a companion file is generated (using the strfile utility) that stores the offset and length of each quote. To pick a quote, you load just the (relatively small) index file into memory, choose an element at random, then use that offset and length to seek and read a single quote from the appropriate quote file.

Here's a Python implementation of fortune on GitHub. The original C code should be floating around somewhere too.

查看更多
登录 后发表回答