Created
August 21, 2013 02:17
-
-
Save woodnathan/6289692 to your computer and use it in GitHub Desktop.
NSString+Canonical
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import <Foundation/Foundation.h> | |
| @interface NSString (Canonical) | |
| - (NSString *)canonicalizedString; | |
| @end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import "NSString+Canonical.h" | |
| @implementation NSString (Canonical) | |
| - (NSString *)canonicalizedString | |
| { | |
| NSCharacterSet *set = [NSCharacterSet alphanumericCharacterSet]; | |
| NSString *lowercaseString = self.lowercaseString; | |
| NSRange range = NSMakeRange(0, lowercaseString.length); | |
| unichar *inputBuffer = malloc(range.length * sizeof(unichar)); | |
| [lowercaseString getCharacters:inputBuffer range:range]; | |
| unichar *outputBuffer = calloc(1, range.length * sizeof(unichar)); | |
| size_t bufferOffset = 0; | |
| for (NSUInteger i = 0; i < range.length; i++) | |
| { | |
| unichar character = inputBuffer[i]; | |
| if ([set characterIsMember:character]) | |
| outputBuffer[bufferOffset++] = character; | |
| } | |
| NSString *canonicalizedString = [[NSString alloc] initWithCharacters:outputBuffer length:bufferOffset]; | |
| free(inputBuffer); | |
| free(outputBuffer); | |
| return canonicalizedString; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment