用“和”替换字符串中的最后一个逗号。 (目标C)

时间:2022-02-28 22:31:33

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

我正在寻找Objective-C中的一个好方法,用单词“and”替换字符串中的最后一个逗号。有什么建议么?

"Red, Green, Blue, Yellow"

“红色,绿色,蓝色,黄色”

becomes

"Red, Green, Blue and Yellow"

“红色,绿色,蓝色和黄色”

1 个解决方案

#1


60  

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

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

#1


60  

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

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