2014-12-01 25 views
0

我正在製作一個「每天都有新詞」的程序,並從large text file中隨機選取一個詞。從.txt文件中讀取一行數字

它是這樣工作在C#:

int randomword = word.Next(1, 58110); // Pick a random valid line (last is 58110) 
string[] lines = File.ReadAllLines(dictionarypath); // Read all lines into an array 
string word = lines[randomword]; // take the chosen line from the array 

所以,基本上,它創建一個數組,並從中選擇一個隨機線。
我想在Objective-C中做到這一點。

有沒有辦法做到這一點?
更重要的是,有沒有快速的方法來做到這一點?

+0

什麼是你的問題?用什麼語言?你有多遠?顯示一些。順便說一句:你的年齡和缺乏與提出可接受問題有關的經驗如何? – Deduplicator 2014-12-01 20:14:03

+0

使用標準I/O工具以任何通用語言無法通過行號讀取文件的特定行。必須以某種方式讀取整個文件和計數行。 – 2014-12-01 20:25:12

+0

@Deduplicator我修復了這個問題,希望現在更清楚。 – 2014-12-02 22:12:36

回答

2

請參閱下面的示例代碼: -

NSString* filePath = @""// your file path... 
NSString* fileRoot = [[NSBundle mainBundle]pathForResource:filePath ofType:@"txt"]; 

// Now for reading everything from text 
NSString* fileContents = 
[NSString stringWithContentsOfFile:fileRoot encoding:NSUTF8StringEncoding error:nil]; 

// Now, separate by new line 
NSArray* allLinedStrings = 
[fileContents componentsSeparatedByCharactersInSet: 
[NSCharacterSet newlineCharacterSet]]; 

//Now Iterating and printing 
for (NSString *ln in allLinedStrings) 
{ 
    NSLog(@"%@",ln); 
} 
+0

我在哪裏可以輸入行號? – 2014-12-01 21:22:35

+0

您可以根據您的要求放置 – 2014-12-01 22:04:44