How to read a random line from a textfile?

2019-06-14 14:31发布

问题:

I'm a absolute beginner to Xcode and Objective-C, hey that sounded like the book I'm reading by Rory Lewis ! I'm trying to write a simple question game for IOS.

This is my first app, except a few versions "Hello world" ;-) I have read a large number of forums, and I haven't yet found what I'm looking for.

So I would like to read out a random line from a plain textfile, let's say "file.txt" wich contains about 500 lines. When I press a button, I would like the app to fetch a random line from the file.txt and present it on the screen. I have tried a number things, and I feel that I'm just fumbling in the dark ! Hoping someone will point me in the right direction (a basic one please ;-).

回答1:

Something like this should work:

#include <stdlib.h>
#include <time.h>

NSString *file = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];

NSString *fileContents = [NSString stringWithContentsOfFile:file];

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

 /* initialize random seed: */
  srand ( time(NULL) );

  /* generate random number: */
  int index = rand() % [lines count];

NSString *string = [lines objectAtIndex:index];