Obj-C:用NSDictionary对象替换两个子串 - 只有一个在改变

时间:2015-12-12 03:18:22

标签: objective-c nsstring nsdictionary

有一个有趣的问题。我有一个NSDictionary,例如:

self.abbreviations = @{
                        @"REGL"     :   @"REGIONAL",
                        @"REG"      :   @"REGIONAL",
                        @"RE"       :   @"REGIONAL",
                        @"CO"       :   @"COUNTY",
}

如果在字符串中记下缩写,我想使用以下命令将其替换为全名:

if ([destination containsString:[NSString stringWithFormat:@" %@,",key]])
        {
            destinationRev = [[destination stringByReplacingOccurrencesOfString:@"," withString:@" "]mutableCopy];
        }

for (id key in self.abbreviations)
{
    if ([destinationRev containsString:[NSString stringWithFormat:@" %@ ", key]])
    {
        destination = [destinationRev stringByReplacingOccurrencesOfString:key
                                                                withString:[self.abbreviations objectForKey:key]];
    }
}

但是对于名称:CITY CO REGL,我有以下输出:CITY CO REGIONAL。即,虽然CO位于两个空格之间,但CO没有变化。

我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

您将单个替换的结果分配给引用destination,保持destinationRev不变,并在每个循环运行中覆盖destination。因此,您只能获得最后一次替换的字符串。

for (id key in self.abbreviations)
{
  if ([destinationRev containsString:[NSString stringWithFormat:@" %@ ", key]])
  {
    /* ---> */ destinationRev = [destinationRev stringByReplacingOccurrencesOfString:key
                                                            withString:[self.abbreviations objectForKey:key]];
  }
}