I would choose another approach:
NSString *placeResult = @"Starbucks, 222 Main Street, Cupertino, CA";
// Split the NSString into an NSArray out of parts of the NSString
NSArray *parts = [placeResult componentsSeparatedByString:@","];
// This NSMutableString will store our edited string
NSMutableString *result = [[NSMutableString alloc] init];
// If there are only 3 NSStrings in parts it is only `Address`, `City` and `State`
// so we can use it as is
if (parts.count == 3)
[result appendString:placeResult];
// If there are 4 NSStrings in parts there is something in front of we don't need,
// so we need to cut it off
else if (parts.count == 4) {
// We start at `index 1` because at `index 0` is the element we don't want
int startIndex = 1;
// Here we append the first part and after that increment our index
[result appendFormat:@"%@", parts[startIndex++]];
// We loop through the NSArray starting at `index 2`, our next element
for (; startIndex < parts.count; startIndex++)
// We append our new element with a comma in front of it
// Note that the string we append still starts with a space so we don't insert one here
[result appendFormat:@",%@",parts[startIndex]];
// Now our string is completely stored in `result`.
// What we need to do now is cut off the first space which was included
// when we inserted the first element before the loop.
// I mean this space: @"Starbucks, 222 Main Street, Cupertino, CA";
// ↑
// Our NSString usually does always has a space in front, so this if-clause is a little superfluous but in case you get a string without a space after every comma this cuts off your first letter
if ([[result substringWithRange:NSMakeRange(0, 1)] isEqualToString:@" "])
// Delete the first character which definitely is a space
[result deleteCharactersInRange:NSMakeRange(0, 1)];
}
// I'm pretty sure what we do here ;)
NSLog(@"%@", result);
Output:
for @"111 Main Street, Cupertino, CA"
:
111 Main Street, Cupertino, CA
for @"Starbucks, 222 Main Street, Cupertino, CA"
:
222 Main Street, Cupertino, CA
Edit: This code does exactly what you want ;)