替换字符串中的字符 [英] Replace character in string

查看:131
本文介绍了替换字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSMutableString @hello。我想替换第二个位置的字符,'e'替换为'a',以便它读取 @hallo

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?

我已经尝试过实现一个Shift Cipher,但它抛出一个 IndexOutBoundsException / p>

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;

}


推荐答案

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

另外,请学习使用在线参考。

Also, do learn to use the online reference.

这篇关于替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆