0

If you have a list like apple,orange,lemon, you can change it to apple, orange and lemon in Objective-C using:

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

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

Is there an efficient way to do this in Swift?

I can replace the last element of the array with 'and lemon' by converting the string into an array using

 var arr = str.components(separatedBy: ",")
                               

But I am struggling with how to remove the last comma.

Thanks for any suggestions.

user6631314
  • 1,751
  • 1
  • 13
  • 44
  • 1
    The same approach would work with Swift, compare e.g. https://stackoverflow.com/q/26411635/1187415 for how to search for the last occurrence of a comma in the string. – Martin R Jun 22 '20 at 16:53
  • Thanks I used the extension in the linked to answer – user6631314 Jun 22 '20 at 17:07
  • @user6631314 https://stackoverflow.com/a/41819176/2303865 – Leo Dabus Jun 22 '20 at 17:22
  • Yes, if you want a nicely localized string, it is `NSArray *strings = [str componentsSeparatedByString:@","];` and `[NSListFormatter localizedStringByJoiningStrings:strings]` as noted in https://stackoverflow.com/a/62412873/1271826. – Rob Aug 24 '21 at 19:05

0 Answers0