ROT13编码/解码字符串,但不更改括号[]内的字符

时间:2015-09-29 18:08:29

标签: ios objective-c regex encoding nsstring

我有一个简单的ROT13方法,可以对字符串进行编码或解码。

+ (NSString *)ROT13encodeString:(NSString *)aString {

    if (!aString) {
        return nil;
    }

    // Find text between brackets
    NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"[]"];
    NSArray *splitString = [aString componentsSeparatedByCharactersInSet:delimiters];
    // ???

    NSString *newString;
    unsigned length;
    unichar *buf;
    unsigned i;

    length = [aString length];
    buf = malloc( (length + 1) * sizeof(unichar) );
    [aString getCharacters:buf];
    buf[length] = (unichar)0; // not really needed....
    for (i = 0; i < length; i++) {
        if (buf[i] >= (unichar)'a' && buf[i] <= (unichar) 'z') {
            buf[i] += 13;
            if (buf[i] > 'z') buf[i] -= 26;
        } else if (buf[i] >= (unichar)'A' && buf[i] <= (unichar) 'Z') {
            buf[i] += 13;
            if (buf[i] > 'Z') buf[i] -= 26;
        }
    }
    newString = [NSString stringWithCharacters:buf length:length];
    free(buf);
    return newString;

}

但是,在要编码的文本中,括号[]中有“安全”字样。包括括号在内的单词不应该被编码,它们总是需要处于非编码状态。

我想我可以取出括号内文字的所有遗嘱,但不确定它会有什么帮助:

NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"[]"];
NSArray *splitString = [aString componentsSeparatedByCharactersInSet:delimiters];

如何修改我当前的方法以包含此内容?

1 个答案:

答案 0 :(得分:1)

我没有在objective-c中编码,但我认为这应该很接近:

+ (NSString *)ROT13encodeString:(NSString *)aString {

    if (!aString) {
        return nil;
    }

    // Find text between brackets
    NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"[]"];
    NSArray *splitString = [aString componentsSeparatedByCharactersInSet:delimiters];
    // ???

    NSString *newString;
    unsigned length;
    unichar *buf;
    unsigned i;
    unsigned level;

    length = [aString length];
    buf = malloc( (length + 1) * sizeof(unichar) );
    [aString getCharacters:buf];
    buf[length] = (unichar)0; // not really needed....
    level = 0;
    for (i = 0; i < length; i++) {
        if (buf[i] == (unichar)'[') {
          level++;
        } else if (buf[i] == (unichar)']') {
          level--;
        } else if (level==0 && buf[i] >= (unichar)'a' && buf[i] <= (unichar) 'z') {
            buf[i] += 13;
            if (buf[i] > 'z') buf[i] -= 26;
        } else if (level==0 && buf[i] >= (unichar)'A' && buf[i] <= (unichar) 'Z') {
            buf[i] += 13;
            if (buf[i] > 'Z') buf[i] -= 26;
        }
    }
    newString = [NSString stringWithCharacters:buf length:length];
    free(buf);
    return newString;

}