Snilleblixten
Snilleblixten

Reputation: 1305

Replace last comma in string with an "and". (Objective-C)

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"

Upvotes: 28

Views: 6743

Answers (2)

Kelan
Kelan

Reputation: 2276

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

Upvotes: 0

mvds
mvds

Reputation: 47034

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

if(lastComma.location != NSNotFound) {
    str = [str stringByReplacingCharactersInRange:lastComma
                                       withString: @" and"];
}

Upvotes: 65

Related Questions