NSString Category for create revsered string and lexically sorted string.
This file contains 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
/* | |
NSString+SPUtils | |
Category for NSString | |
-reversedString | |
: create reversed string. | |
NSString *reversed = [@"AbcdE" reversedString]; // reversed = @"EdcbA" | |
: create lexically sorted string. | |
NSString *sorted = [@"ae3ceox" sortedString]; // sorted = @"3aceeox" | |
23. 04. 13. | |
by sooop. | |
*/ | |
#import <Foundation/Foundation.h> | |
@interface NSString (SPUtils) | |
-(NSString*)reversedString; | |
-(NSString*)sortedString; | |
@end; | |
@implementation NSString (SPUtils) | |
-(NSString*)reversedString | |
{ | |
NSUInteger length = [self length], idx; | |
char *cString = (char*)malloc(sizeof(char)*(length+1)); | |
strcpy(cString,[self UTF8String]); | |
char temp; | |
for(idx=0;idx<length/2;idx++) { | |
temp = *(cString + idx); | |
*(cString + idx) = *(cString + length - 1 - idx); | |
*(cString + length - 1 - idx) = temp; | |
} | |
NSString *reversedString = [NSString stringWithUTF8String:cString]; | |
free(cString); | |
return reversedString; | |
} | |
-(NSString*)sortedString | |
{ | |
NSString *resultString; | |
@autoreleasepool { | |
NSMutableArray *characters = [NSMutableArray array]; | |
NSArray *sortedArray; | |
NSUInteger idx; | |
for(idx=0;idx<[self length];idx++) { | |
[characters addObject:[self substringWithRange:NSMakeRange(idx,1)]]; | |
} | |
NSSortDescriptor *strDiscriptor = [[NSSortDescriptor alloc] initWithKey:@"description" ascending:YES]; | |
NSArray *discs = @[strDiscriptor]; | |
sortedArray = [characters sortedArrayUsingDescriptors:discs]; | |
NSMutableString *string = [NSMutableString string]; | |
for(idx=0;idx<[self length];idx++) { | |
[string appendString:[sortedArray objectAtIndex:idx]]; | |
} | |
resultString = [string copy]; | |
} | |
#if __has_feature(objc_arc) | |
return resultString; | |
#else | |
return [resultString autorelease]; | |
#endif | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment