siamii
siamii

Reputation: 24094

Replace character in string

I have a NSMutableString @"hello". I'd like to replace the character at the second position, 'e' with 'a' so that it reads @"hallo". How do I do that?

I have tried this to implement a Shift Cipher, but it throws an 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;

}

Upvotes: 1

Views: 2232

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61351

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

Also, do learn to use the online reference.

Upvotes: 3

Cesar A. Rivas
Cesar A. Rivas

Reputation: 1355

You can use stringByReplacingOccurrencesOfString:withString: of NSString.

Upvotes: 2

Related Questions