Replacing multiple characters in NSString by multiple other characters using a dictionary

别说谁变了你拦得住时间么 提交于 2019-11-29 12:13:27

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];
       }
}];

First Replace Every "1" by "9" and then Replace Every "a" by "1". Whats wrong with the logic ?

Your Dictionary is

@"1", @"a",
@"2", @"b",
@"3", @"c",
@"9", @"1",
@"8", @"2",
@"7", @"3",
nil

Replacing "1" by "9" will create

@"9", @"a",
@"2", @"b",
@"3", @"c",
@"9", @"9",
@"8", @"2",
@"7", @"3",
nil

and then Replacing "a" by "1" will create

@"9", @"1",
@"2", @"b",
@"3", @"c",
@"9", @"9",
@"8", @"2",
@"7", @"3",
nil

Do you want this as your Desired result ?

If ur rule is static like u said...i dont have sure if it is better

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

for (NSInteger i = 0; i < string.length; i++)
{

    unichar cu = [string characterAtIndex:i];
    if (cu >=97 && cu<=99){
        cu -= 48;
    }else if (cu>=49 && cu<=51){
        cu = cu+10-((cu-48)*2);
    }
    [newString appendString:[NSString stringWithFormat:@"%C",cu]];
}

NSLog(@"newString: %@", newString);

I'm using ASCII codes to match ur exactly rule.

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