有没有办法从NSString获取拼写检查数据?

时间:2011-03-11 00:55:47

标签: objective-c cocoa cocoa-touch

我正在编写一个简单的移位密码iPhone应用程序作为宠物项目,我正在设计的一项功能是NSString的“通用”解密,它返回NSArray,所有NSStrings:

- (NSArray*) decryptString: (NSString*)ciphertext{
NSMutableArray* theDecryptions = [NSMutableArray arrayWithCapacity:ALPHABET];

for (int i = 0; i < ALPHABET; ++i) {
    NSString* theNewPlainText = [self decryptString:ciphertext ForShift:i];

    [theDecryptions insertObject:theNewPlainText
                         atIndex:i];
}
return theDecryptions;

}

我真的想把这个NSArray传递给另一个尝试拼写检查数组中每个字符串的方法,并构建一个新的数组,将字符串中最少的字符串放在较低的标记处,这样它们'先重新显示。我想像文本字段一样使用系统的字典,所以我可以匹配用户训练到手机中的单词。

我目前的猜测是将给定的字符串拆分为单词,然后使用NSSpellChecker的-checkSpellingOfString:StartingAt:进行拼写检查,并使用正确的单词数对数组进行排序。是否有现有的库方法或广为接受的模式,有助于为给定的字符串返回这样的值?

1 个答案:

答案 0 :(得分:2)

好吧,我发现了一个使用UIKit / UITextChecker的解决方案。它正确地找到了用户最喜欢的语言字典,但我不确定它是否包含实际rangeOfMisspelledWords...方法中的学习单词。如果没有,在底部if语句中调用currentWord上的[UITextChecker hasLearnedWord]应该足以找到用户教授的单词。

正如评论中所述,谨慎使用rangeOfMisspelledWords中的前几种语言拨打[UITextChecker availableLanguages]以帮助多语言用户。

-(void) checkForDefinedWords {
    NSArray* words = [message componentsSeparatedByString:@" "];
    NSInteger wordsFound = 0;
    UITextChecker* checker = [[UITextChecker alloc] init];
    //get the first language in the checker's memory- this is the user's
    //preferred language.
    //TODO: May want to search with every language (or top few) in the array
    NSString* preferredLang = [[UITextChecker availableLanguages] objectAtIndex:0];

    //for each word in the array, determine whether it is a valid word
    for(NSString* currentWord in words){
        NSRange range;
        range = [checker rangeOfMisspelledWordInString:currentWord
                                                 range:NSMakeRange(0, [currentWord length]) 
                                            startingAt:0 
                                                  wrap:NO
                                              language:preferredLang];

        //if it is valid (no errors found), increment wordsFound
        if (range.location == NSNotFound) {
            //NSLog(@"%@ %@", @"Valid Word found:", currentWord);
            wordsFound++;
        }
        else {
            //NSLog(@"%@ %@", @"Invalid Word found:", currentWord);
        }
    }


    //After all "words" have been searched, save wordsFound to validWordCount
    [self setValidWordCount:wordsFound];

    [checker release];
}
相关问题