gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:37:02 25 4
gpt4 key购买 nike

我有一个简单的 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];

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

最佳答案

我不在 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;

}

关于ios - ROT13 编码/解码字符串但不更改括号 [] 内的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com