28

I'm looking for a good way in Objective-C to replace the last comma in a string with the word "and". Any suggestions?

"Red, Green, Blue, Yellow"

becomes

"Red, Green, Blue and Yellow"

2 Answers 2

65
NSString *str = @"....";  
NSRange lastComma = [str rangeOfString:@"," options:NSBackwardsSearch];

if(lastComma.location != NSNotFound) {
    str = [str stringByReplacingCharactersInRange:lastComma
                                       withString: @" and"];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wonderful solution! Thanks for a fast answer :)
What if the last item has a comma? For instance, this 3-item list: @"Apple, Falls, Far, far away."
0

As of iOS 13, there is now built-in support for this: (NS)ListFormatter, which, aside from being less code, also handles localization.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.