gpt4 book ai didi

kotlin - 检查 Kotlin 中的字符串是否为空

转载 作者:IT老高 更新时间:2023-10-28 13:28:52 28 4
gpt4 key购买 nike

在 Java 中,我们一直被提醒使用 myString.isEmpty() 来检查字符串是否为空。然而,在 Kotlin 中,我发现您可以使用 myString == ""myString.isEmpty() 甚至 myString.isBlank() .

对此是否有任何指导方针/建议?或者它只是“任何能撼动你的船的东西”?

提前感谢您满足我的好奇心。 :D

最佳答案

不要使用 myString == "",在 java 中这将是 myString.equals(""),也不推荐使用。

isBlankisEmpty 不同,它确实取决于您的用例。

isBlank 检查 char 序列的长度是否为 0 或所有索引都是空白。 isEmpty 只检查 char 序列长度是否为 0。

/**
* Returns `true` if this string is empty or consists solely of whitespace characters.
*/
public fun CharSequence.isBlank(): Boolean = length == 0 || indices.all { this[it].isWhitespace() }


/**
* Returns `true` if this char sequence is empty (contains no characters).
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.isEmpty(): Boolean = length == 0

关于kotlin - 检查 Kotlin 中的字符串是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45336954/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com