Skip to content

Instantly share code, notes, and snippets.

@dautermann
Created April 10, 2013 12:31
Show Gist options
  • Save dautermann/5354205 to your computer and use it in GitHub Desktop.
Save dautermann/5354205 to your computer and use it in GitHub Desktop.
Given an array of strings, e.g.: NSArray * files = @"[@"file2", @"folder22", @"folder10", @"file1", @"folder100", … … …, nil]; Describe how you would write some kind of method or function that would sort the strings in a predictable manner (e.g. "file1", "file2", "folder2", "folder10", "folder100" instead of "folder10", "folder100", "folder2")
- (NSComparisonResult)fileNameCompare:(NSString *)aString
{
NSComparisonResult result;
// split string1 and string2 each into two halves
//
// then compare string1 and string2's halves with each other
NSString * firstHalfOfSelf = [NSString getFirstHalfOf: self];
NSString * firstHalfOfOtherString = [NSString getFirstHalfOf: aString];
result = [firstHalfOfSelf compare: firstHalfOfOtherString];
if(result == NSOrderedSame)
{
NSString * secondHalfOfSelf = [NSString getSecondHalfOf: self];
NSString * secondHalfOfOtherString = [NSString getSecondHalfOf: aString];
NSInteger selfValue = [secondHalfOfSelf integerValue];
NSInteger otherStringValue = [secondHalfOfOtherString integerValue];
if(selfValue > otherStringValue)
{
result = NSOrderedDescending;
} else {
if(selfValue == otherStringValue)
{
result = NSOrderedSame;
} else {
result = NSOrderedAscending;
}
}
}
return(result);
}
// these methods pretty much assume that all input strings
// are in the form of letters + numbers (e.g. "abcdef1234")
//
// proper production code would do more error checking
+ (NSString *) getFirstHalfOf: (NSString *) someString
{
NSString * stringToReturn;
// create substring up to (but not including) the numeric portion of the name
NSRange firstNumberCharacter = [someString rangeOfCharacterFromSet: [NSCharacterSet decimalDigitCharacterSet]];
if(firstNumberCharacter.location != NSNotFound)
{
stringToReturn = [someString substringToIndex: firstNumberCharacter.location];
} else {
stringToReturn = someString;
}
return(stringToReturn);
}
+ (NSString *) getSecondHalfOf: (NSString *) someString
{
NSString * stringToReturn;
// create substring starting with the numeric portion of the name
NSRange firstNumberCharacter = [someString rangeOfCharacterFromSet: [NSCharacterSet decimalDigitCharacterSet]];
if(firstNumberCharacter.location != NSNotFound)
{
stringToReturn = [someString substringFromIndex: firstNumberCharacter.location];
} else {
stringToReturn = someString;
}
return(stringToReturn);
}
@dautermann
Copy link
Author

And yes, after I typed all this code out... I was informed that the best answer is simply that the NSString method "compare: options:" has an option of NSNumericSearch that does exactly what I needed to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment