原文: https://www.programiz.com/kotlin-programming/examples/string-empty-null
在此程序中,您将学习使用if-else语句和 Kotlin 中的函数检查字符串是否为空或null。
示例 1:检查字符串是否为空或null
fun main(args: Array<String>) {val str1: String? = nullval str2 = ""if (isNullOrEmpty(str1))println("str1 is null or empty.")elseprintln("str1 is not null or empty.")if (isNullOrEmpty(str2))println("str2 is null or empty.")elseprintln("str2 is not null or empty.")}fun isNullOrEmpty(str: String?): Boolean {if (str != null && !str.isEmpty())return falsereturn true}
运行该程序时,输出为:
str1 is null or empty.str2 is null or empty.
在上面的程序中,我们有两个字符串str1和str2。str1包含空值,str2是空字符串。
我们还创建了一个函数isNullOrEmpty(),顾名思义,该函数检查字符串是空还是空。 它使用字符串的!= null和isEmpty()方法使用空检查来对其进行检查。
简而言之,如果字符串不是null且isEmpty()返回false,则它既不是null也不为空。 否则,是的。
但是,如果字符串仅包含空格字符(空格),则上述程序不会返回空。 从技术上讲,isEmpty()看到它包含空格并返回false。 对于带空格的字符串,我们使用字符串方法trim()修剪掉所有前导和尾随空格字符。
示例 2:检查带空格的字符串是否为空或null
fun main(args: Array<String>) {val str1: String? = nullval str2 = " "if (isNullOrEmpty(str1))println("str1 is null or empty.")elseprintln("str1 is not null or empty.")if (isNullOrEmpty(str2))println("str2 is null or empty.")elseprintln("str2 is not null or empty.")}fun isNullOrEmpty(str: String?): Boolean {if (str != null && !str.trim().isEmpty())return falsereturn true}
运行该程序时,输出为:
str1 is null or empty.str2 is null or empty.
在isNullorEmpty()中,我们添加了一个额外的方法trim(),该方法删除了给定字符串中的所有前导和尾随空白字符。
因此,现在,如果字符串仅包含空格,该函数将返回true。
以下是等效的 Java 代码:检查字符串是否为 null 或为空的 Java 程序。
