2013-07-13 14 views

回答

2

一個想法是在單個字符以取代字母序列的每一次出現和 計數結果的長度:

NSString *string = @"Hello world"; 
NSMutableString *tmp = [string mutableCopy]; 
NSArray *sequences = @[@"ll", @"wo"]; 
for (NSString *seq in sequences) { 
    [tmp replaceOccurrencesOfString:seq 
         withString:@"." 
          options:NSCaseInsensitiveSearch 
           range:NSMakeRange(0, [tmp length])]; 
} 
// tmp is "He.o .rld" now 
NSUInteger length = [tmp length]; 

備註:length不計數「組成的字符」作爲單個字符。 如果這是一個問題,你必須使用enumerateSubstringsInRange:options:usingBlock:NSStringEnumerationByComposedCharacterSequences選項將 字符準確計數。這例如適用於所有「UTF-16」代理對(例如Emojis)。它可能適用於其他字符,如韓文字符爲好, 我不知道現在是正確的。

ADDED:以下方法使用正則表達式,並且應該也能正常工作。 優點可能是沒有創建臨時字符串。但應該測量哪種方法真的更快。

NSString *string = @"Hello world"; 

NSString *pattern = @"ll|wo|."; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern 
                     options:NSRegularExpressionCaseInsensitive 
                     error:NULL]; 
NSUInteger length = [regex numberOfMatchesInString:string 
              options:0 
              range:NSMakeRange(0, [string length])]; 


NSLog(@"length = %d", length); 
+0

有趣。有數百個字符串來計算長度,你認爲這是最理想的方式嗎?謝謝。 – Pablo

+0

@Pablo:我仍在想如果我能找到更好的方法。你有多少個「字母序列」?對所有要測試的字符串,字母序列是否相同? –

+0

實際上只是一個字母序列。是的,所有要測試的字符串都是一樣的。 – Pablo