使用字典用多个其他字符替换NSString中的多个字符 [英] Replacing multiple characters in NSString by multiple other characters using a dictionary

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

问题描述

我想用字典替换我的字符串中的一些字符,其他字符。

I would like to replace some characters in my string, by other characters, using a dictionary.

例如,每个a应该替换为1 ,每个1应该用9代替。我不想要的是每次a被替换两次,最后是9。每个角色必须只更换一次。

For instance, every "a" should be replaced by "1", and every "1" should be replaced by "9". What I don't want is every "a" to be replaced twice, ending up with a "9". Every character must be replaced just once.

我使用以下代码完成了这项工作,但我觉得它可以更高效地完成。
这真的是我能做的最好的,还是可以帮我改进代码?

I got this working using the following code, but I feel like it can be done more efficient. Is this really the best I can do, or can you help me improve my code?

NSDictionary *replacements = [NSDictionary dictionaryWithObjectsAndKeys:
                              // Object, Key,
                              @"1", @"a",
                              @"2", @"b",
                              @"3", @"c",
                              @"9", @"1",
                              @"8", @"2",
                              @"7", @"3",
                              nil];

NSString *string = @"abc-123";
NSMutableString *newString = [NSMutableString stringWithCapacity:0];

for (NSInteger i = 0; i < string.length; i++)
{
    NSString *c = [NSString stringWithFormat:@"%C", [string characterAtIndex:i]];
    id replacement = [replacements objectForKey:c];
    if (replacement != nil) {
        [newString appendString:replacement];
    } else {
        [newString appendString:c];
    }
}

NSLog(@"newString: %@", newString); // newString: 123-987 (Works!)

为了清楚起见:此代码适用于我,我觉得它效率很低。我正在寻找改善它的方法。

Just to be clear: This code is working for me, I just feel like it's very inefficient. I'm Looking for ways to improve it.

谢谢。

推荐答案

以下代码可能不会快得多,但稍微简单一些。
它使用一个方法正确地计算字符串的所有字符,即使使用
组成的字符,例如Emojis(在字符串中存储为两个字符)。

The following code is perhaps not much faster, but slightly simpler and shorter. It enumerates all characters of the string with a method that works correctly even with composed characters such as Emojis (which are stored as two characters in the string).

NSMutableString *newString = [string mutableCopy];

[newString enumerateSubstringsInRange:NSMakeRange(0, [newString length])
                  options:NSStringEnumerationByComposedCharacterSequences
               usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
       NSString *repl = replacements[substring];
       if (repl != nil) {
           [newString replaceCharactersInRange:substringRange withString:repl];
       }
}];

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

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