0

在我的 iOS 应用程序中,我想从 google API 附近拆分单词,api 结果显示如下,

 "vicinity" : "24/49,TV Swamy Road East,, TV Swamy Street, RS Puram, Coimbatore"
 "vicinity" : "48, T.V. Swamy Road West, T.V. Swamy Road (West), Near Tasmac, R.S. Puram, Coimbatore"
 "vicinity" : "Diwan Bhadur Road, RS Puram, Coimbatore"
 "vicinity" : "Avinashi Road, P.S.G. College Stop, Avinashi Road, Near P.S.G. Optical Centre, Peelamedu, Coimbatore"

这是我尝试用来修剪的代码

 __block NSString *lastWord = nil;

[str enumerateSubstringsInRange:NSMakeRange(0, [str length]) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
    lastWord = substring;
    *stop = YES;
}];

但结果如下

 Coimbatore
 Coimbatore
 Coimbatore
 Coimbatore

我只想显示上述结果中的修剪细节,如下所示

 "TV Swamy Street, RS Puram, Coimbatore"
 "R.S. Puram, Coimbatore"
 "RS Puram, Coimbatore"
 "Peelamedu, Coimbatore"

如何修剪像上面这样的细节?

4

1 回答 1

0

目前尚不清楚您裁剪字符串的逻辑是什么。如果你只想要最后两个组件,你可以这样做

NSArray *results = @[@{@"vicinity" : @"24/49,TV Swamy Road East,, TV Swamy Street, RS Puram, Coimbatore"},
  @{@"vicinity" : @"48, T.V. Swamy Road West, T.V. Swamy Road (West), Near Tasmac, R.S. Puram, Coimbatore"},
  @{@"vicinity" : @"Diwan Bhadur Road, RS Puram, Coimbatore"},
  @{@"vicinity" : @"Avinashi Road, P.S.G. College Stop, Avinashi Road, Near P.S.G. Optical Centre, Peelamedu, Coimbatore"}];

    NSMutableArray *formattedResults = [NSMutableArray array];
    for (NSDictionary *dict in results) {
        NSString *vicinity = dict[@"vicinity"];

        NSArray *components = [vicinity componentsSeparatedByString:@","];
        NSUInteger length = 2;
        if ([components count]<length) {
            break;
        }
        NSRange range = NSMakeRange([components count]-length, length);
        NSArray *croppedComponents = [components subarrayWithRange:range];

        NSString *croppedVicinity = [croppedComponents componentsJoinedByString:@","];

        if (croppedVicinity) {
            [formattedResults addObject:croppedVicinity];
        }
    }

    NSLog(@"%@",formattedResults);
于 2013-10-07T08:47:23.347 回答