将密码范围移出界限
我正在尝试实现一个移位密码,这意味着将字符串中的每个字符移动一定的量。我正确编写的方法替换了第一个字母,但在第二次迭代时它抛出了 Range out ofbounds
异常。
original = @"rt"
第一次将r
替换为w
。 t
第二次不会被 y
替换。
移位=5
#define LETTER_POS 97
#define ALPHABET_LENGTH 26
- (NSString*)encode:(NSString*)original withShift:(int)shift {
NSMutableString* encoded = [NSMutableString stringWithString:original];
for (int i=0; i < [encoded length]; i++) {
char oriChar = [encoded characterAtIndex:i];
if (oriChar == ' ') {
continue;
}
char encChar = ((oriChar - LETTER_POS) + shift) % ALPHABET_LENGTH + LETTER_POS;
NSRange range = {i, i+1};
[encoded replaceCharactersInRange:range withString:[NSString stringWithFormat:@"%c" , encChar]];
}
return encoded;
}
I'm trying to implement a Shift Cipher, which means, shift every character in a string by an amount. The method I wrote correctly replaces the first letter, but on the second iteration it throws a Range out of bounds
exception.
original = @"rt"
The first time r
is replaced by w
. t
isn't replaced by y
the second time.
shift = 5
#define LETTER_POS 97
#define ALPHABET_LENGTH 26
- (NSString*)encode:(NSString*)original withShift:(int)shift {
NSMutableString* encoded = [NSMutableString stringWithString:original];
for (int i=0; i < [encoded length]; i++) {
char oriChar = [encoded characterAtIndex:i];
if (oriChar == ' ') {
continue;
}
char encChar = ((oriChar - LETTER_POS) + shift) % ALPHABET_LENGTH + LETTER_POS;
NSRange range = {i, i+1};
[encoded replaceCharactersInRange:range withString:[NSString stringWithFormat:@"%c" , encChar]];
}
return encoded;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSRange 有一个位置和一个长度。您使用 i+1 作为长度,因此在第二次迭代中您要求提供超出字符串末尾的字符。你的范围应该是{i, 1}。
NSRange has a location, and a length. You are using i+1 as the length, so in your second iteration you are asking for characters past the end of the string. Your range should be {i, 1}.