Created
February 13, 2015 08:05
-
-
Save StefanLage/a034ac56bee641463c26 to your computer and use it in GitHub Desktop.
Reverse an NSString using XOR swap (import file: https://gist.github.com/StefanLage/febc88228b548689571d)
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
#import <Foundation/Foundation.h> | |
@interface NSString (Reverse) | |
+(NSString*)stringReverse:(NSString*)str; | |
@end |
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
#import "NSString+Reverse.h" | |
#import "NSString+Char.h" | |
@implementation NSString (Reverse) | |
/* | |
* Reverse a NSSTRing using XOR swap | |
* which means we need to first convert it as a char pointer to work with bits | |
*/ | |
+(NSString*)stringReverse:(NSString*)str{ | |
char *cWord = [str toChar]; | |
size_t len = strlen(cWord); | |
int start = 0; | |
int end = (int)len-1; | |
while (start<end) { | |
cWord[start] ^= cWord[end]; | |
cWord[end] ^= cWord[start]; | |
cWord[start] ^= cWord[end]; | |
start++; | |
end--; | |
} | |
char reverseData[len]; | |
memcpy(reverseData, cWord, len); | |
NSString *reverse = [[NSString alloc] initWithBytes:reverseData | |
length:sizeof(reverseData) | |
encoding:NSUTF8StringEncoding]; | |
return reverse; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment