Skip to content

Instantly share code, notes, and snippets.

@klmitchell2
Last active June 15, 2017 00:32
Show Gist options
  • Save klmitchell2/7223eff3a234f6ac2927c44721a61e2c to your computer and use it in GitHub Desktop.
Save klmitchell2/7223eff3a234f6ac2927c44721a61e2c to your computer and use it in GitHub Desktop.
Caesar Cipher written in Objective-C
- (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