我正在编写一个简单的移位密码 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:
对每个单词进行拼写检查,并使用正确单词的数量对数组进行排序。是否存在有助于为给定字符串返回此类值的现有库方法或广为接受的模式?
最佳答案
好吧,我找到了一个使用 UIKit/UITextChecker 的解决方案。它正确地找到了用户最喜欢的语言词典,但我不确定它是否在实际的 rangeOfMisspelledWords...
方法中包含学到的单词。如果没有,在底部 if 语句中的 currentWord 上调用 [UITextChecker hasLearnedWord]
应该足以找到用户教授的单词。
如评论中所述,谨慎的做法是使用 [UITextChecker availableLanguages]
中的每种前几种语言调用 rangeOfMisspelledWords
,以帮助多语言用户。
-(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];
}
关于objective-c - 有没有办法从 NSString 获取拼写检查数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5267834/