问题描述
String.length/1
函数以 UTF-8 二进制格式返回字素的数量。
如果我想知道字符串中有多少个 Unicode 代码点,我知道我可以这样做:
string |> String.codepoints |> length
但是这会产生一个不必要的所有代码点的中间列表并迭代字符两次。有没有一种方法可以直接计算代码点,而无需生成中间列表?
解决方法
您可以使用带有位串生成器的 comprehension 和 reduce
选项来计算代码点,而无需构建中间列表。
for <<_::utf8 <- string>>,reduce: 0,do: (count -> count + 1)
示例:
iex> string = "??♂️"
iex> for <<_::utf8 <- string>>,do: (count -> count + 1)
5
iex> string |> String.codepoints |> length
5
iex> String.length(string)
1
如果将 utf8
替换为 utf16
或 utf32
,它还有一个额外的好处,它也适用于 UTF-16 和 UTF-32 字符串:
iex> utf8_string = "I'm going to be UTF-16!"
"I'm going to be UTF-16!"
iex> utf16_string = :unicode.characters_to_binary(utf8_string,:utf8,:utf16)
<<0,73,39,109,32,103,111,105,110,116,98,101,85,84,70,45,49,54,33>>
iex> for <<_::utf8 <- utf8_string>>,do: (count -> count + 1)
23
iex> for <<_::utf16 <- utf16_string>>,do: (count -> count + 1)
23