定义字符、字符串
1 2 3 4 5
| val hello = "你好 8ug.icu"
val char = 'C'
|
字符串长度:length & count()
1 2 3 4 5 6
| val length = hello.length
val length2 = hello.count()
println("length = $length, length2 = $length2")
|
字符串拼接 & 模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| println("hello ".plus("www.8ug.icu")) println("hello " + "www.8ug.icu")
val bug = "www.8ug.icu"
println("hello $bug")
val strTemple = """ 众鸟高飞尽, 孤云独去闲。 相看两不厌, 只有敬亭山。 """.trimIndent()
println(strTemple)
|
字符查找:first()、firstOrNull()、first{}、last()、lastOrNull()、find{}、indexOf()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| val firstChar = hello.first() println(firstChar)
println("".firstOrNull())
val firstChar2 = hello.first { it == '你' } println(firstChar2)
val lastChar = hello.last() println(lastChar)
hello.lastOrNull() hello.lastOrNull { it == 'u' }
hello.find { it == '你' }
val index: Int = hello.indexOf('你')
println("字符第一次出现的下标 = $index")
|
字符串截取 substring()、subSequence()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
val substr = hello.substring(0,2) println("截取的字符 = $substr")
val substr2 = hello.substring(IntRange(0,2)) println("截取的字符2 = $substr2")
val substr3 = hello.subSequence(0,2) println("截取的字符3 = $substr3")
|
字符串替换:replace()、replaceFirst()、replaceAfter()、replaceAfterLast()、replaceBefore()、replaceBeforeLast()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
val replaceStr = hello.replace('u','U') println("替换字符 = $replaceStr")
val replaceStr2 = hello.replace('U','哈', true) println("替换字符 = $replaceStr2")
println(hello.replace("你好", "Hello"))
println("ii".replaceFirst('i','I'))
println("uiuiui".replaceAfter('u',"X"))
println("uiuiui".replaceAfter('a',"X"))
println("uiuiui".replaceAfter("a","X", "AA"))
println("uui".replaceAfterLast('u',"X"))
println("hello 888ug.icu".replaceBefore('8',"B"))
println("hello 888ug.icu".replaceBeforeLast('8',"B"))
|
字符串分割 split()
1 2 3 4 5 6 7 8 9 10
|
println("hello 8ug.icu".split(" "))
println("hello 8ug.icu".split(Pattern.compile("")))
|
字符串验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
println("".isBlank()) println("".isNotBlank()) println("".isEmpty()) println("".isNotEmpty())
val nullStr: String? = null
println(nullStr?.isBlank())
println(nullStr.isNullOrEmpty()) println(nullStr.isNullOrBlank())
|
Demo: https://github.com/hefengbao/kotlin-demo.git