1

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;

}
jscs
  • 63,694
  • 13
  • 151
  • 195
siamii
  • 23,374
  • 28
  • 93
  • 143
  • possible duplicate of [Replacing one character in a string - iPhone/iPad](http://stackoverflow.com/questions/5223701/replacing-one-character-in-a-string-iphone-ipad) – jscs Oct 29 '11 at 16:59

2 Answers2

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

Also, do learn to use the online reference.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • 1
    Or use [AppKiDo](http://homepage.mac.com/aglee/downloads/appkido.html) for reference, it's free and uses the Apple documentation. – zaph Oct 29 '11 at 16:39
2

You can use stringByReplacingOccurrencesOfString:withString: of NSString.

Cesar A. Rivas
  • 1,355
  • 1
  • 10
  • 13