【问题标题】:What is different between isEmpty and isBlank in kotlinkotlin 中的 isEmpty 和 isBlank 有什么区别
【发布时间】:2020-09-07 13:48:21
【问题描述】:

我想在我的 Android 项目中检查字符串的值。我看到了两个函数来检查我的字符串值:

item.isBlank()

item.isEmpty()

它们有什么区别?

【问题讨论】:

标签: android kotlin


【解决方案1】:

item.isEmpty() 只检查字符串的长度

item.isBlank() 检查长度并且所有字符都是空格

也就是说

  • " ".isEmpty() 应该返回 false
  • " ".isBlank() 应该返回 true

来自isBlank的文档

如果此字符串为空或仅包含空格,则返回 true 字符。

【讨论】:

    【解决方案2】:

    以后,您可以阅读文档并从 IDE 中查看代码,只需单击 Ctrl+B 或 Command+B。这是在 isEmpty 方法的文档中编写的:

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

    对于 isBlank:

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

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 2018-12-22
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多