我有一个简单的字符串,列出用逗号分隔的项目。在最后一项之前,我想包括“和”这个词。
以逗号分隔的字符串示例:
green apple, red strawberry, orange grapefruit, yellow banana
我想改为显示:
green apple, red strawberry, orange grapefruit, and yellow banana
另外,如果只有两个项目我想删除逗号(即青苹果和红色草莓)。
关于我如何开始这个的任何想法?
谢谢!
答案 0 :(得分:0)
一种方法是使用文本项分隔符,计算数字,然后处理每种情况。假设没有无关的逗号。
set s to "green apple, red strawberry, orange grapefruit, yellow banana"
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ","
set s to text items of s
set n to count of s
if n = 1 then
set r to s as string
else if n = 2 then
set r to item 1 of s & " and" & item 2 of s
else
set item -1 of s to (" and" & item -1 of s)
set r to s as string
end if
set AppleScript's text item delimiters to otid
return r