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

标签 objective-c string cocoa nsstring

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

相关文章:

ios - 按下按钮时如何更改图像?

string - 字符串不可变有什么优势?

objective-c - 我应该明确释放吗?

objective-c - NSView subview 的 Alpha 值

ios - 使用本地时区推送通知

ios - 你如何使用 Storyboard引用 UISearchController

ios - UI : iOS 中动态数据的 UI 单元测试失败

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

python - 将日期时间字符串转换为日期时间

cocoa - 在核心数据文档中存储文档特定设置的最佳方法是什么?