首页 文章

检查Kotlin中字符串是否为空

提问于
浏览
18

在Java中,我们总是被提醒使用 myString.isEmpty() 来检查String是否为空 . 然而,在Kotlin中,我发现你可以使用 myString == ""myString.isEmpty() 甚至 myString.isBlank() .

对此有任何指导/建议吗?或者它只是“任何晃动你的船”?

提前感谢我的好奇心 . :d

3 回答

  • 5

    不要使用 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
    
  • 24

    对于String? (nullable String)数据类型,我用 .isNullOrBlank()

    对于String,我使用 .isBlank()

    为什么?因为大多数时候,我不想允许带有空格的字符串(并且 .isBlank() 检查空格以及空字符串) . 如果您不关心空格,请使用 .isNullorEmpty().isEmpty() 作为字符串?和String,分别 .

  • 13

    如果要测试String是否与空字符串 "" 完全相等,请使用 isEmpty .

    如果要测试String为空或仅包含空格( """ " ),请使用 isBlank .

    避免使用 == "" .

相关问题