如何从文本文件读取随机行? [英] How to read a random line from a textfile?

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

问题描述

我是绝对的Xcode和Objective-C的初学者,嘿,听起来像我正在阅读罗里·刘易斯的书!我试图为iOS写一个简单的问题游戏。



这是我的第一个应用程序,除了几个版本Hello world;-)我读了一个大的论坛的数量,我还没有找到我要找的东西。

所以我想从一个纯文本文件读出一个随机的行,让我们来说file.txt至少包含500行。当我按下按钮时,我希望应用程序从file.txt中获取一个随机的行并将其显示在屏幕上。我尝试了一些东西,我觉得我只是在黑暗中摸索!希望有人会指出我正确的方向(一个基本的请; - )。

解决方案

这样的事情应该工作: / b>

  #include  
#include

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

NSString * fileContents = [NSString stringWithContentsOfFile:file];

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

/ *初始化随机种子:* /
srand(time(NULL));
$ b / *生成随机数字:* /
int index = rand()%[lines count];

NSString * string = [lines objectAtIndex:index];


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 ;-).

解决方案

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

这篇关于如何从文本文件读取随机行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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