我有一個簡單的ROT13方法來編碼或解碼字符串。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;
}
但是,在要編碼的文本中,放置在方括號[]中的是「安全」字。包括括號在內的單詞不應編碼,它們總是需要處於非編碼狀態。
我想我可以拉出來的括號內的文本的所有occururances,但不知道它是如何幫助:
NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"[]"];
NSArray *splitString = [aString componentsSeparatedByCharactersInSet:delimiters];
我怎麼能修改我目前的方法,包括本?
我不會理會分裂的字符串。當你找到一個'['並且當你找到''''''''''''''''''''''''''''''''''''取決於你是否想要處理嵌套括號,可能必須稍微複雜一些。 – dan
同意丹。使用'NSScanner'可能會讓你的整體生活更輕鬆。 –