如何使用A1Z26密码解码NSString?

时间:2018-01-02 20:37:23

标签: javascript objective-c cryptography equivalent

我正在尝试使用A1Z26密码解码(只有a = 1,b = 2,...,z = 26)。输入文本用连字符分隔,如下所示:

-8-16-2-7-8-5-

我有JavaScript解决了这个问题,但我似乎无法在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;
}

Objective C中的等效代码是什么样的?

1 个答案:

答案 0 :(得分:-1)

在目标C中,可以按如下方式进行:

-(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];
}

请注意,这假设输入已具有正确的格式。它会愉快地接受"--42-df-w---wf"形式的字符串。

编辑:如果有多个可能的分隔符(例如连字符和空格),则可以使用NSCharacterSet

-(NSString *)decode:(NSString *)input {
    NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString: @"- "];
    NSArray<NSString *> *components = [input componentsSeparatedByCharactersInSet:separatorSet];
    ...
}