How to sort a NSArray alphabetically?

前端 未结 7 1225
借酒劲吻你
借酒劲吻你 2020-11-22 15:32

How can I sort an array filled with [UIFont familyNames] into alphabetical order?

7条回答
  •  星月不相逢
    2020-11-22 16:20

    This already has good answers for most purposes, but I'll add mine which is more specific.

    In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".

    This does that for you.

    It would probably be best to put these in categories.

    // Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.
    
    -(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {
    
        NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
    
            //find the strings that will actually be compared for alphabetical ordering
            NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
            NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];
    
            return [firstStringToCompare compare:secondStringToCompare];
        }];
        return sortedArray;
    }
    
    // Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.
    
    -(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
        NSString* result;
        if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
            result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        }
        else {
            result = originalString;
        }
        return result;
    }
    

提交回复
热议问题