Replace character in string

南笙酒味 提交于 2019-12-11 11:01:58

问题


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:


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

Also, do learn to use the online reference.




回答2:


You can use stringByReplacingOccurrencesOfString:withString: of NSString.



来源:https://stackoverflow.com/questions/7940104/replace-character-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!