English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Colección completa de ejemplos de Kotlin
Kotlin程序检查字符串是否为空或null-在这个程序中,您将学习使用Kotlin中的if
Ejemplo : String? = null1fun main(args: Array<String>) { : String? = null2 :检查字符串是否为空或null if (isNullOrEmpty(str1)) println("str1= "" else println("str1no es null o vacío." if (isNullOrEmpty(str2)) println("str2es null o vacío." else println("str2no es null o vacío." } fun isNullOrEmpty(str: String?): Boolean { es null o vacío." return false return true }
Al ejecutar el programa, la salida es:
str1Es null o vacío. str2Es null o vacío.
if (str != null && !str.isEmpty())1在上面的程序中,我们有两个字符串str2和str1。str2包含null值,str
是一个空字符串。
我们还创建了一个函数isNullOrEmpty(),顾名思义,该函数检查字符串是null还是空。 它使用!= null和string的isEmpty()方法进行null检查来对其进行检查
简单地说,如果一个字符串不是null并且isEmpty()返回false,那么它既不是null也不是空。否则,是的。
Ejemplo : String? = null1fun main(args: Array<String>) { : String? = null2 val str if (isNullOrEmpty(str1)) println("str1es null o vacío." else println("sstr2no es null o vacío." if (isNullOrEmpty(str2)) println("str2es null o vacío." else println("str2no es null o vacío." } fun isNullOrEmpty(str: String?): Boolean { if (str != null && !str.trim().isEmpty()) return false return true }
Al ejecutar el programa, la salida es:
str1Es null o vacío. str2Es null o vacío.
En isNullorEmpty(), hemos agregado un método adicional trim(), que elimina todos los caracteres de espacio en blanco al principio y al final de la cadena dada.
Si la cadena solo contiene espacios, la función devuelve true.
Este es el código Java equivalente:Programa Java para verificar si una cadena es null o vacía。