gpt4 book ai didi

objective-c - 替换字符串中的字符

转载 作者:行者123 更新时间:2023-12-03 16:52:53 25 4
gpt4 key购买 nike

我有一个 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;

}

最佳答案

NSRange r = {1,1}; //String indexing is 0-based
[s replaceCharactersInRange: r withString:@"a"]

此外,请务必学习使用在线引用。

关于objective-c - 替换字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7940104/

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