2012-10-15 42 views
0

我想將nsstring中的每個字符逐個與不同的nscharactersets進行比較,並根據匹配的字符集執行不同的操作。將nsstring中的字符與不同的字符集進行比較

我可以使用for循環將每個字符分配給一個子字符串進行比較。

- (void) compareCharactersOfWord: (NSString *) word { 

    for (int i = 0; i<[word length]; i++) { 

     NSString *substring = [word substringWithRange:NSMakeRange(i,1)]; 


     //need to compare the substring to characterset here 

    } 
} 

我也有我的兩個charactersets

setOne = [[NSCharacterSet characterSetWithCharactersInString:@"EAIONRTLSU"]invertedSet]; 

setTwo = [[NSCharacterSet characterSetWithCharactersInString:@"DG"] invertedSet]; 

我有點失去了對比較部分。我嘗試了不同的方法,如「rangeOfCharacterFromSet」,但我一直在獲取erros。在僞代碼,我需要像

if (setOne containsCharacterFrom substring) { 

//do stuff here 

} else if (setTwo containsCharacterFrom substring) { 

//do other stuff here 

} 

回答

1

要看看你的「子串'變量你可以這樣做:

if ([substring rangeOfCharacterFromSet:setOne].location != NSNotFound) { 
    // substring is in setOne 
} else if ([substring rangeOfCharacterFromSet:setTwo].location != NSNotFound) { 
    // substring is in setTwo 
} 

另一種選擇是使用字符。

for (int i = 0; i<[word length]; i++) { 
    unichar ch = [word characterAtIndex:i]; 

    if ([setOne characterIsMember:ch]) { 
     // in setOne 
    } else if ([setTwo characterIsMember:ch]) { 
     // in setTwo 
    } 
} 

第二個選項有一個很大的限制。它不適用於高於0xFFFF的Unicode字符。

1

您需要從字符串中提取每個字符(unichar),並使用[NSCharacterSet characterIsMember:],以確定是否它要麼NSCharacterSet的一部分:

- (void) compareCharactersOfWord: (NSString *)word 
{ 
    // These could be initialised globally to speed things up a little... 
    NSCharacterSet *setOne = [[NSCharacterSet characterSetWithCharactersInString:@"EAIONRTLSU"] invertedSet]; 
    NSCharacterSet *setTwo = [[NSCharacterSet characterSetWithCharactersInString:@"DG"] invertedSet]; 

    for (NSUInteger index = 0; index < [word length]; index++) 
    { 
     unichar c = [word characterAtIndex:index]; 
     if ([setOne characterIsMember:c]) 
     { 
      // c is a member of character set #1 
     } 
     else if ([setTwo characterIsMember:c]) 
     { 
      // c is a member of character set #2 
     } 
     else 
     { 
      // c is a member of neither character set 
     } 
    } 
} 
相關問題