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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…