检查Kotlin中字符串是否为空

Aba*_*Aba 29 kotlin

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

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

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

Cha*_*ham 36

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

isBlank是不一样的isEmpty,它实际上取决于你的用例.

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
Run Code Online (Sandbox Code Playgroud)

  • 我绝对忘记了`myString.equals("")`。我猜是因为我从来没有在 Java 中这样做过,因为我被告知不要这样做。感谢您的提醒和清晰的解释! (2认同)
  • 从 Kotlin 1.3 开始,甚至有一个新的扩展函数可用,它是 `ifBlank`,它允许你在主值为空时分配一个默认字符串 (2认同)

Eri*_*ber 16

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

对于String,我使用 .isBlank()

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


Pix*_*ant 6

使用isEmpty时要测试一个字符串正好等于空字符串"".

使用isBlank时要测试一个字符串为空或只包含空格的(""," ").

避免使用== "".


小智 6

Kotlin 中有两种可用的方法。

  1. isNullOrBlank()
  2. isNullOrEmpty()

区别在于:

data = " " // this is a text with blank space 
 
println(data.isNullOrBlank()?.toString())  //true
println(data.isNullOrEmpty()?.toString())  //false
Run Code Online (Sandbox Code Playgroud)