Instantly share code, notes, and snippets.

Embed
What would you like to do?
NSString Category for create revsered string and lexically sorted string.
/*
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)]];
}
sortedArray = [characters sortedArrayUsingComparator:^(NSString *a, NSString*b) {
return [a compare:b];
}];
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