Reputation: 1336
I am googling NSSting manipulation methods from last few hours. and found many on stack overflow like this here
I have a String "1800 Ellis St, San Francisco, CA 94102, USA". String may have any number of "," . I have to take the third last(San Franncisco) and last(USA) substring after ",".
and output should be "San Franncisco USA".
I have logic how to do this in my mind that but I am struggling to implement it.
I try this code for getting the position of last three "," in string. but it's not work for me
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;
}
}
}
Thanks
Upvotes: 0
Views: 163
Reputation: 81848
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'"];
Upvotes: 1
Reputation: 726479
You can do it like this:
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!";
}
The componentsSeparatedByString:
will split the string at ,
, and stringWithFormat:
will put the parts back together.
Upvotes: 2
Reputation: 3937
Try this:
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];
Upvotes: 0