2011-08-25 81 views
3

我對SO有很好的搜索,但找不到與此問題相關的任何內容。我有一個自定義對象類,實現了在數組中進行排序的比較方法。此比較使用NSCaseInsensitiveSearch類的「name」屬性。代碼如下所示:用數字排序的字符串最後一個目標c

- (NSComparisonResult)compare:(Forum *)otherObject { 
return [self.name compare:otherObject.name options:(NSCaseInsensitiveSearch)]; 
} 

但是,使用NSCaseInsensitiveSearch會將數字字符串放在帶字母的字符串之前。有沒有辦法做到這一點相反,以便數字在字母后面出現?

回答

1

不要只

return [self.name compare:otherObject.name options:(NSCaseInsensitiveSearch)]; 

但做一些額外的檢查,例如如果self.name以非數字開頭,otherObject.name以數字開頭,則返回NSDescendingOrder,反之亦然。 IOW,使數字>非數字。如果兩者都是非數字或兩者都是數字,請返回您已有的數字。

這個小控制檯程序解釋我的意思是這樣的原則:

#import <Foundation/Foundation.h> 

int main (int argc, const char * argv[]) 
{ 

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    NSMutableArray *array = [NSMutableArray arrayWithObjects: 
          @"Adam", @"001", @"Bertha", @"3SeriesBMW", @"Colin", 
          @"Zelda", @"1And1", @"Xaver", @"Kraftwerk", @"TangerineDream", 
          @"5SeriesBMW", @"0ableTypes", nil]; 

    NSString *sortOrder = @"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz_"; 

    [array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) 
    { 
     char char1 = [(NSString *)obj1 characterAtIndex: 0]; 
     char char2 = [(NSString *)obj2 characterAtIndex: 0]; 

     int index1; 
     for (index1 = 0; index1 < sortOrder.length; index1++) 
      if ([sortOrder characterAtIndex: index1] == char1) 
       break; 

     int index2; 
     for (index2 = 0; index2 < sortOrder.length; index2++) 
      if ([sortOrder characterAtIndex: index2] == char2) 
       break; 

     if (index1 < index2) 
      return NSOrderedAscending; 
     else if (index1 > index2) 
      return NSOrderedDescending; 
     else 
      return [(NSString *)obj1 compare: obj2 options: NSCaseInsensitiveSearch]; 
    }]; 

    for (NSString *s in array) 
     NSLog(@"%@", s); 

    [pool drain]; 
    return 0; 
} 

輸出是:

2011-08-25 14:19:15.538 NumeralSort[5802:707] Adam 
2011-08-25 14:19:15.540 NumeralSort[5802:707] Bertha 
2011-08-25 14:19:15.540 NumeralSort[5802:707] Colin 
2011-08-25 14:19:15.540 NumeralSort[5802:707] Kraftwerk 
2011-08-25 14:19:15.541 NumeralSort[5802:707] TangerineDream 
2011-08-25 14:19:15.541 NumeralSort[5802:707] Xaver 
2011-08-25 14:19:15.541 NumeralSort[5802:707] Zelda 
2011-08-25 14:19:15.542 NumeralSort[5802:707] 001 
2011-08-25 14:19:15.542 NumeralSort[5802:707] 0ableTypes 
2011-08-25 14:19:15.542 NumeralSort[5802:707] 1And1 
2011-08-25 14:19:15.543 NumeralSort[5802:707] 3SeriesBMW 
2011-08-25 14:19:15.543 NumeralSort[5802:707] 5SeriesBMW 

這是不完全的解決方案,但應該讓你對你的方式。

+0

這工作的一種享受,感謝您的幫助! – steemcb

+0

我如何在NSSortDescriptor中使用它? – Raj

1

使用256-(16位)字符轉換數組(假設您只有標準的ASCII字符)轉換要比較的字符串。將大多數字符轉換爲它們自己的值(或小寫,同時處理不區分大小寫的函數),但將數字轉換爲它們的值加上一些數字(例如0xF000)。然後做字符串比較。

如果您有超出ASCII範圍的字符,請一次翻譯一個字符,將字符完全複製(或更低 - 大小寫)爲非數字,然後複製字符作爲字符值加上該大數字數字。

相關問題