2011-03-11 110 views
5

我正在寫一個簡單的移位密碼的iPhone應用程序作爲寵物項目,功能,我目前正在設計一個部分是一個NSString的「通用」解密,返回一個NSArray,所有NSString的的:有沒有辦法從NSString獲取拼寫檢查數據?

- (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傳遞到試圖拼寫檢查陣列中的每個單獨的字符串,並建立一個新的陣列,在低放串用最少typo'd字的另一種方法指示,所以他們首先顯示。我想使用系統字典,就像文本字段一樣,所以我可以匹配用戶已經通過手機培訓過的單詞。

我目前的猜測是將給定的字符串拆分成單詞,然後拼寫檢查每個與NSSpellChecker的-checkSpellingOfString:StartingAt:並使用正確的單詞數排序數組。有沒有一種現有的庫方法或普遍接受的模式可以幫助爲給定的字符串返回這樣的值?

回答

2

那麼,我找到了一個使用UIKit/UITextChecker的解決方案。它正確地找到了用戶最喜歡的語言字典,但我不確定它是否包含實際的rangeOfMisspelledWords...方法中的學習單詞。如果沒有,在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]; 
} 
相關問題