Last active
June 15, 2017 00:32
-
-
Save klmitchell2/7223eff3a234f6ac2927c44721a61e2c to your computer and use it in GitHub Desktop.
Caesar Cipher written in Objective-C
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 *)caesarCipher:(int)shift { | |
if (self.length == 0) { | |
return nil; | |
} | |
//no shift, return unencrypted string | |
if (shift == 0){ | |
return self; | |
} | |
//create empty mutable string with capacity of the length | |
NSMutableString *str = [[NSMutableString alloc] init]; | |
for (int i = 0; i < self.length; i++) { | |
[str insertString:@" " atIndex:i]; | |
} | |
for (int i = 0; i < self.length; i++) { | |
//if i + shift results in going out of bounds | |
if (i+shift > self.length-1) { | |
int wrapIndex = abs((int)(i+shift - self.length)); | |
[str insertString:[NSString stringWithFormat:@"%c", [self characterAtIndex:i]] atIndex:wrapIndex]; | |
} else { | |
[str insertString:[NSString stringWithFormat:@"%c", [self characterAtIndex:i]] atIndex:i+shift]; | |
} | |
} | |
NSString *result = [str stringByReplacingOccurrencesOfString:@" " withString:@""]; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment