为什么 Elixir 的 String.capitalize() 函数将剩余字母小写?

Why does Elixir's String.capitalize() function lowercase remaining letters?

Elixir 的 String.capitalize/2 函数“将给定字符串中的第一个字符转换为大写,将其余字符转换为小写”。将第一个字符大写并保持其余字符不变不是更直观吗?也许我缺少一些推理?

当前的实施结果为 the local ATM -> The local Atmforgotten PIN -> Forgotten Pin

这是长生不老药 api,需要进行 capitalisation。

def capitalize(string, mode) when is_binary(string) do
    {char, rest} = String.Casing.titlecase_once(string, mode)
    char <> downcase(rest, mode)
end

如果我们想要满足您的要求,即只计算 api 首字母,那么我们可以执行类似的操作。在这里,我们只删除了额外的下套管调用,因此我们只使这段代码在性能方面更加健壮。

def capitalize_only_first(string, mode) when is_binary(string) do
    {char, rest} = String.Casing.titlecase_once(string, mode)
    char <> rest
end

从性能的角度来看,第二种实现更好。所以,我认为保留这个 capitalize/2 由 elixir 实现的唯一原因是因为大多数开发人员都希望它以这种方式工作。

这个答案让我普遍对可能绕过它的推理感到好奇。 :)

对于希望在不编写自定义函数的情况下执行此操作的任何人,以下是我在需要时执行此操作的方法:

"the local ATM"
|> String.Casing.titlecase_once(:default)
|> Tuple.to_list 
|> Enum.join

任何在谷歌上搜索这个的人的 JFYI :)

更新:不要这样做!根据 https://elixirforum.com/t/string-capitalize-should-have-a-leave-the-rest-of-the-word-alone-option/31095/2?u=slouchpie 使用 Casing.titlecase_once

是危险的

这是一个解决方案,不需要调用未记录的特定实现 String.Casing

with <<c :: utf8, rest :: binary>> <- "the local ATM",
  do: String.upcase(<<c>>) <> rest

#⇒ "The local ATM"

以上内容也适用于 unicode 字符(组合和分解):

with <<c :: utf8, rest :: binary>> <- "über BVG",
  do: String.upcase(<<c>>) <> rest

#⇒ "Über BVG"