I'm trying to decode an using the A1Z26 cipher (which is just a=1, b=2, ..., z=26). The input text is separated by hyphens, like this:
-8-16-2-7-8-5-
I have JavaScript which solves this problem, but I cannot seem to get a version working in Objective C
function a1z26Cipher(inputString) {
var outputString = "";
var splitString = inputString.split(/(\W| )/);
for (var i = 0; i < splitString.length; i++) {
var n = splitString[i];
if (n >= 1 && n <= 26) outputString += String.fromCharCode(parseInt(n, 10) + 64);
else outputString += n.replace("-", "");
}
return outputString;
}
What would equivalent code in Objective C look like?
In Objective C this can be done as follows:
-(NSString *)decode:(NSString *)input {
NSArray<NSString *> *components = [input componentsSeparatedByString:@"-"];
NSMutableString *output = [[NSMutableString alloc] init];
for (NSString *component in components) {
if (component.length == 0) {
continue;
}
char charValue = (char) [component intValue];
[output appendFormat:@"%c", charValue + ('a' - 1)];
}
return [NSString stringWithString:output];
}
Note that this assumes the input already has the correct format. It will accept strings of the form "--42-df-w---wf"
happily.
EDIT: If there are multiple possible separators (e.g. hyphen and space), you can use NSCharacterSet
:
-(NSString *)decode:(NSString *)input {
NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString: @"- "];
NSArray<NSString *> *components = [input componentsSeparatedByCharactersInSet:separatorSet];
...
}