Mos*_*atz 6 string title-case kotlin
使用 Kotlin 1.5 时,Android Studio 会警告该版本String.capitalize已弃用。
建议的替换是:
myString.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() })
Run Code Online (Sandbox Code Playgroud)
为什么需要检查isLowerCase?
为什么我不能这样做:
myString.replaceFirstChar { it.titlecase(Locale.getDefault()) })
Run Code Online (Sandbox Code Playgroud)
门票中的报价:
\n\n\n此外,用户可能对 的行为有不同的期望
\nfun String.capitalize(): String,并且这些期望并不总是与我们实现的一致(请参阅KEEP讨论)。仅当接收者的第一个字符为小写字母时,该函数才会将String其首字母大写。例如,结果"\xc7\x84".capitalize()是"\xc7\x84",而"\xc7\x86".capitalize()是"\xc7\x85"。考虑到不同的期望,我们想引入replaceFirstChar函数来让用户准确地编写他们想要的代码。
\n\n替换内容很冗长,但尽可能保留行为。如果需要更简单的行为,例如,可以进一步简化生成的代码
\nString.replaceFirstChar { it.uppercaseChar() }。
以下是根据我的想法的原始答案。另请检查评论,因为有一个很好的注释\xef\xac\x80:
我想这是因为他们想复制原始行为。目前capitalize 实施为:
public fun String.capitalize(locale: Locale): String {\n if (isNotEmpty()) {\n val firstChar = this[0]\n if (firstChar.isLowerCase()) {\n return buildString {\n val titleChar = firstChar.titlecaseChar()\n if (titleChar != firstChar.uppercaseChar()) {\n append(titleChar)\n } else {\n append(this@capitalize.substring(0, 1).uppercase(locale))\n }\n append(this@capitalize.substring(1))\n }\n }\n }\n return this\n}\nRun Code Online (Sandbox Code Playgroud)\n另外,根据注释:
\n\n\n字符的标题大小写通常与其大写相同,但有几个例外。
\n
有一些极端情况:
\nfun check(x: String) {\n println(x.capitalize())\n println(x.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() })\n println(x.replaceFirstChar { it.titlecase() })\n}\n\nfun main() {\n check("\xc7\xb3")\n check("\xc7\xb1")\n}\nRun Code Online (Sandbox Code Playgroud)\n输出(游乐场):
\n\xc7\xb2\n\xc7\xb2\n\xc7\xb2\n\xc7\xb1\n\xc7\xb1\n\xc7\xb2\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
6516 次 |
| 最近记录: |