在字符串替换字符(Replace character in string)

2019-09-26 10:04发布

我有一个NSMutableString @"hello" 。 我想在第二位置与“A”,使其读取替换字符,“E” @"hallo" 。 我怎么做?

我曾经尝试这样做,以实现移位密码,但它抛出一个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;

}

Answer 1:

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

此外,请学会使用网上参考。



Answer 2:

您可以使用stringByReplacingOccurrencesOfString:withString:的的NSString 。



文章来源: Replace character in string