Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

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

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

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.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...