我有NSMutableString
@"hello"
。我想替换第二个位置的字符,'e'替换为'a',以便它显示为@"hallo"
。我该怎么做?
我试过这个来实现一个Shift Cipher,但它抛出一个IndexOutBoundsException
- (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};
[encoded replaceCharactersInRange:range withString:[NSString stringWithUTF8String:&encChar]];
}
return encoded;
}
答案 0 :(得分:3)
NSRange r = {1,1}; //String indexing is 0-based
[s replaceCharactersInRange: r withString:@"a"]
另外,请务必学习使用在线参考资料。
答案 1 :(得分:2)
您可以使用NSString的stringByReplacingOccurrencesOfString:withString:
。