views:

192

answers:

2

I have an array with a list of objects sorted alphabetically ignoring the letters case (used a lowerCaseString method) and I need to sort it into an array of arrays one for each letter +1 for non alpha characters.

A simple way of doing it would be to loop through the source array with a giant 27 stack deep if else if else if else.... Needless to say I don't think that's a very good solution so I was thinking if I could convert the first letter of the string that I'm sorting by to an int I could then use that to calculate an index to sort the object into.

So I need help with either implementing this or finding a better way to do it.

I'm working on the iPhone platform so I have access to the cocoa and core apple librarys.

+2  A: 

In regular c, str[0] - 'a' would give you an integer from 0 to 25 for strings starting with lowercase-alpha characters. Then you just have one if to check for non-alpha initial characters.

Anon.
+2  A: 

You can use a "sorted" NSMutableArray and it would hold your 27 "letter" NSMutableArray objects that each hold your objects.

You can also use an NSArray of the 26 letters (as NSString objects) and use indexOfObject: to get the index from the "sorted" array of the "letter" array that object should be added to (if it returns NSNotFound, use 26 as the index since that's your non-alpha array).

For example, if you are sorting NSString objects, you could do it like this:

NSArray *originalArray = [NSArray arrayWithObjects:@"A object",@"B object",@"C object",@"123 object",nil];

// init with all 26 lowercase letters here
NSArray *letters = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];

// create sorted and letter arrays
NSMutableArray *sortedArray = [[NSMutableArray alloc] initWithCapacity:[letters count]+1];
for (int i = 0; i < [letters count] + 1; i++) {
    // use an appropriate capacity here
    NSMutableArray *letterArray = [[NSMutableArray alloc] initWithCapacity:10];
    [sortedArray addObject:letterArray];
    [letterArray release];
}

// sort originalArray into sortedArray
for (NSString *string in originalArray) {
    NSString *firstLetter = [[string substringWithRange:[string rangeOfComposedCharacterSequenceAtIndex:0]] lowercaseString];

    int index = [letters indexOfObject:firstLetter];
    if (index == NSNotFound) {
        // use non-alpha array
        index = [letters count];
    }

    NSMutableArray *letterArray = [sortedArray objectAtIndex:index];
    [letterArray addObject:string];
}

NSLog(@"%@",sortedArray);
gerry3
Thanks a lot for that, worked a treat.
Affian