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

Obj-C: Replacing two substrings with NSDictionary objects -- only one is changing

有一个有趣的问题。我有一个 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 在两个空间之间,但它没有变化。

我错过了什么?

谢谢!

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

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