我正在谷歌搜索过去几个小时的 NSSting 操作方法。并发现很多像这样的堆栈溢出 here
我有一个字符串 “1800 Ellis St, San Francisco, CA 94102, 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;
}
}
}
谢谢
最佳答案
你可以这样做:
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:
会将这些部分重新组合在一起。
关于iphone - 在 NSString 中出现一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12179518/