字符串拼接
1
| println("明年${age + 1}岁时,$name 将在 $city 庆祝生日。")
|
长度
length:获取字符串长度。
1 2
| val str = "Hello" val length = str.length
|
截取/替换/包含
substring:获取子字符串。
1 2
| val str = "Hello, World!" val sub = str.substring(7)
|
contains:判断字符串是否包含特定子字符串。
1 2
| val str = "Hello, World!" val contains = str.contains("World")
|
replace:替换字符串中的内容。
1 2
| val str = "Hello, Kotlin!" val newStr = str.replace("Kotlin", "World")
|
大小写
toUpperCase 和 toLowerCase:将字符串转换为大写或小写。
1 2 3
| val str = "Hello" val upper = str.toUpperCase() val lower = str.toLowerCase()
|
去空
trim:去除字符串两端的空白字符。
1 2
| val str = " Hello, World! " val trimmed = str.trim()
|
分割
split:根据指定的分隔符拆分字符串为数组。
1 2
| val str = "apple,banana,orange" val fruits = str.split(",")
|
类型转换
toInt、toDouble、toFloat 等:将字符串转换为相应的数字类型。
1 2
| val str = "42" val num = str.toInt()
|
判断空
在 Kotlin 中,可以使用以下方法来判断一个字符串是否为空或者空字符串:
使用 isEmpty() 方法:该方法用于检查字符串是否为空字符串,即长度是否为 0。
1 2 3 4 5 6
| val str = "" if (str.isEmpty()) { } else { }
|
使用 isNullOrEmpty() 方法:该方法用于同时检查字符串是否为 null 或为空字符串。
1 2 3 4 5 6
| val str: String? = null if (str.isNullOrEmpty()) { } else { }
|
使用 isNullOrBlank() 方法:该方法用于检查字符串是否为 null、空字符串或只包含空白字符。
1 2 3 4 5 6
| val str = " " if (str.isNullOrBlank()) { } else { }
|
简便写法
1
| val cover = subTextbook.cover.ifEmpty { bookSetting.cover }
|
NULL字符串默认值
Kotlin中的?:就相当于JS中||
1
| val appSizeStr = appItem.appSizeStr ?: ""
|
字符串转整数
建议先转Float再传Int。
1
| rateStr.toFloat().toInt()
|
注意
字符串直接调用toInt(),如果字符串本身是浮点数的字符串,就会报错。
方法扩展
浮点数格式化字符串
为 Kotlin 的 Float 和 Double 类型分别定义扩展函数,实现“如果是整数显示整数,否则保留2位小数”的逻辑。
四舍五入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import java.util.Locale
fun Float.toSmartString(): String { return if (this == this.toLong().toFloat()) { this.toLong().toString() } else { String.format(Locale.US, "%.2f", this) } }
fun Double.toSmartString(): String { return if (this == this.toLong().toDouble()) { this.toLong().toString() } else { String.format(Locale.US, "%.2f", this) } }
|
直接截取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import java.math.BigDecimal import java.math.RoundingMode
fun Float.toSmartString(): String { if (this == this.toLong().toFloat()) { return this.toLong().toString() } return BigDecimal(this.toString()) .setScale(2, RoundingMode.DOWN) .toPlainString() }
fun Double.toSmartString(): String { return if (this == this.toLong().toDouble()) { this.toLong().toString() } else { BigDecimal(this) .setScale(2, RoundingMode.DOWN) .toPlainString() } }
|
处理时间
1 2 3 4 5 6 7 8 9
| fun Int.toTimeStr(): String { val minutes = this / 60 val remainingSeconds = this % 60 return if (minutes > 0) { "${minutes}′${remainingSeconds}″" } else { "${remainingSeconds}″" } }
|