# Rot47 an NSString Category

As a JAVA native, i am always a litle worried when doing objective-c... memory leaks and pointers flying at my head...

All comments are welcome on the Category below, the Category functions are correct.

#import "NSString+r47.h"

@implementation NSString (r47)
-(NSString *) r47String
{
const char *_string = [self cStringUsingEncoding:NSASCIIStringEncoding];
int stringLength = [self length];
char newString[stringLength+1];
int x;
for( x=0; x<stringLength; x++ )
{
unsigned int aCharacter = _string[x];
if( 0x20 < aCharacter && aCharacter < 0x7F ) // from ! to ~
newString[x] = (((aCharacter - 0x21) + 0x2F) % 0x5E) + 0x21;
else  // Not an r47 character
newString[x] = aCharacter;
}
newString[x] = '\0';
NSString *rotString = [NSString stringWithCString:newString encoding:NSASCIIStringEncoding];
DLog(@"%@ = %@",self,rotString);
return rotString ;
}

@end


Note, you can also find the code at github

-
I would say it looks ok — as long as you dont use it to gain safety in real world projects. ROT is hardly obfuscating and not secure at all. –  vikingosegundo Jan 2 '13 at 22:51
@Frank, I'd personally avoid using the leading underscore naming on _string here. I think that's distracting, and potentially confusing. –  Nate May 24 '13 at 21:32

This bit looks just a bit suspect:

int stringLength = [self length];
char newString[stringLength+1];


You're using the NSString "length" property to size the C char array allocation. This assumes that the string's "length" value (which reflects number of composed unicode characters) will always be equal to the ASCII encoded length, but that's not necessarily true. This is a case of using a value from one domain in another. NSString provides a method that you should use instead:

int stringLength = [self lengthOfBytesUsingEncoding:NSASCIIStringEncoding];


An equivalent, and probably even clearer way to handle this is to get your length from the C-native function, which makes sense since that's the string you're iterating over in the first place:

size_t stringLength = strlen(_string);

-
+1, thats good info. –  Frank Jan 9 '13 at 5:58