Skip to content

Instantly share code, notes, and snippets.

@StefanLage
Created February 13, 2015 08:05
Show Gist options
  • Save StefanLage/a034ac56bee641463c26 to your computer and use it in GitHub Desktop.
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)
#import <Foundation/Foundation.h>
@interface NSString (Reverse)
+(NSString*)stringReverse:(NSString*)str;
@end
#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