0

我正在谷歌搜索过去几个小时的 NSSting 操作方法。并在这里发现了很多这样的堆栈溢出

我有一个字符串"1800 Ellis St, San Francisco, CA 94102, USA"。字符串可以有任意数量的 "," 。我必须在“,”之后取倒数第三个(旧金山)和最后一个(美国)子字符串。

并且输出应该是“ San Franncisco USA ”。

我有逻辑如何在我的脑海中做到这一点,但我正在努力实现它。

我尝试使用此代码获取字符串中最后三个“,”的位置。但这对我不起作用

 NSInteger commaArr[3];

        int index=0;   
        int commaCount=0;

        for(unsigned int  i =  [strGetCityName length]; i > 0; i--)
        {
            if([strGetCityName characterAtIndex:i] == ',')
            {

                commaArr[index]=i;
                index++;
                ++commaCount;
                if(commaCount == 3)
                {
                    break;
                }
            }
        }

谢谢

4

3 回答 3

2

你可以这样做:

NSString *s = @"1800 Ellis St, San Francisco, CA 94102, USA";
NSArray *parts = [s componentsSeparatedByString:@","];
NSUInteger len = [parts count];
NSString *res;
if (len >= 3) {
    res = [NSString stringWithFormat:@"%@%@", [parts objectAtIndex:len-3], [parts objectAtIndex:len-1]];
} else {
    res = @"ERROR: Not enough parts!";
}

componentsSeparatedByString:在 处拆分字符串,stringWithFormat:并将各部分重新组合在一起。

于 2012-08-29T13:54:22.753 回答
1
NSString *s = @"1800 Ellis St, San Francisco, CA 94102, USA";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(?:[^,]*,)?\\s*([^,]*),\\s*(?:[^,]*),\\s*([^,]*)$" options:0 error:NULL];
NSString *result = [regex stringByReplacingMatchesInString:s options:0 range:NSMakeRange(0, [s length]) withTemplate:@"'$1 $2'"];
于 2012-08-29T14:17:13.513 回答
0

试试这个:

NSString *string = @"1800 Ellis St, San Francisco, CA 94102, USA";
NSArray *components = [string componentsSeparatedByString:@","];
NSString *sanFrancisco = [components objectAtIndex:components.count - 3];
NSString *usa = [components objectAtIndex:components.count - 1];
NSString *result = [sanFrancisco stringByAppendingString:usa];
于 2012-08-29T13:57:18.080 回答