【问题标题】:handling file of Spanish Dictionary西班牙语词典处理文件
【发布时间】:2013-11-06 03:55:11
【问题描述】:

我正在尝试获取包含超过 47,000 个单词(一本字典)的文件的内容。 我的目标是生成一个随机数并将该单词定位在文件的特定行,以便在每次运行程序时获得不同的单词,然后输出该单词。 我一直在研究,但我没有找到任何答案,这是我目前所拥有的,它只需要字符,但我想要单词

//
//  main.m
//  wordaday
//
//  Created by Eddy Guzman on 11/5/13.
//  Copyright (c) 2013 Eddy Guzman. All rights reserved.
//

#import <Foundation/Foundation.h>

bool checkFile( NSString * path)
{
    NSFileManager *filemgr;

    filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: path ] == YES)
    {
        return TRUE;
        NSLog (@"File exists");
    }

    else
    {
        NSLog (@"File not found");
        return false;
    }

}

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // insert code here...
        NSLog(@"Hello, World!");
        NSString * path = @"/Users/eddy30/Eddy's Documents/School/Millersville/Fall2013/wordaday/dictionary.txt";



        if(checkFile(path) == TRUE)
        {
            NSLog(@"WOHOOOO");
        }

        NSString* content = [NSString stringWithContentsOfFile:path];

        //NSFileHandle *myFile = fileHandleForReadingAtPath:path;
        int rand = arc4random_uniform(47049);
        char Word = [content characterAtIndex:rand];


        NSLog(@"Word of the day is: %c", Word);
    }
    return 0;
}

【问题讨论】:

  • 如果您了解到 c 和 Objective-C 不是同一种语言,这将有所帮助。为您正在使用的标签使用正确的标签会让您更快地得到答案。 :)

标签: objective-c string file file-io


【解决方案1】:

在这一步之间:

NSString* content = [NSString stringWithContentsOfFile:path];

还有这一步:

char Word = [content characterAtIndex:rand];
NSLog(@"Word of the day is: %c", Word);

嗯。这很令人困惑。照原样,您将整个文件读入一个名为contentNSString,然后从该NSString 中挑选一个随机字符,并输出它,声称它是一个单词。

您如何实际修复此程序将在很大程度上取决于您正在阅读的文件的格式。您需要一个步骤将content 变成NSStringsNSArray,数组的每个索引代表字典中的不同单词。例如,如果您的文件包含一行中的每个单词,您将需要使用这个不错的方法:

NSArray *arrayOfWords = [content componentsSeperatedByString:@"\n"];

然后你将使用你随机生成的int 作为这个数组的索引,然后像这样记录它:

NSLog(@"Word of the day is: %@", [arrayOfWords objectAtIndex:rand]);

如果原始问题中没有更多详细信息,我就无能为力了。我不知道原始文件的格式。我不知道您声称是字典的原始文件是否包含定义等。但是这个答案解释了您想要做什么的要点。


编辑:请注意,在生成随机数时,您需要这样做:

int rand = arc4random_uniform([arrayOfWords count]-1);

为了避免超出范围的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多