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;

}
1

2 Answers 2

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

Also, do learn to use the online reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Or use AppKiDo for reference, it's free and uses the Apple documentation.
2

You can use stringByReplacingOccurrencesOfString:withString: of NSString.

2 Comments

I see. Can I replace the character only at a specified index?
use 'stringByReplacingOccurrencesOfString:withString:options:range:' instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.