我来这里寻找同一问题的答案,最后进行了更多谷歌搜索,结果发现:http://icu-project.org/apiref/icu4j/com/ibm/icu/text/ListFormatter.html http://icu-project.org/apiref/icu4j/com/ibm/icu/text/ListFormatter.html
该类接受参数two
, start
, middle
, and end
:
- two - 两个项目的字符串,第一个项目包含 {0},第二个项目包含 {1}。
- start - 列表项开头的字符串,其中第一个项包含 {0},其余项包含 {1}。
- middle - 列表项开头的字符串,其中包含 {0} 表示列表的第一部分,{1} 表示列表的其余部分。
- end - 列表项末尾的字符串,其中包含 {0} 表示列表的第一部分,{1} 表示最后一项。
所以,对于英语来说,那就是:
- TWO := "{0} and {1}"
- START := "{0}, {1}"
- MIDDLE := "{0}, {1}"
- END := "{0} and {1}"
我写了一个快速的 Lua 演示来展示我想象的它是如何工作的:
function list_format(words, templates)
local length = #words
if length == 1 then return words[1] end
if length == 2 then
return replace(replace(templates['two'], '{0}', words[1]),
'{1}', words[2])
end
local result = replace(templates['end'], '{1}', words[length])
while length > 3 do
length = length - 1
local mid = replace(templates['middle'], '{1}', words[length])
result = replace(result, '{0}', mid)
end
result = replace(result, '{0}', words[2])
result = replace(templates['start'], '{1}', result)
result = replace(result, '{0}', words[1])
return result
end
function replace(template, index, text)
str, _ = string.gsub(template, index, text)
return str
end
local english = {
["two"] = "{0} and {1}",
["start"] = "{0}, {1}",
["middle"] = "{0}, {1}",
["end"] = "{0} and {1}"
}
print(list_format({"banana"}, english))
print(list_format({"banana", "apple"}, english))
print(list_format({"banana", "apple", "mango"}, english))
print(list_format({"banana", "apple", "mango", "pineapple"}, english))
将其适用于其他语言应该是微不足道的。