kotlin中字符串的定义和操作
fun main() {
val str = "hello world!"
println("str.length:" + str.length)
println("str.substring(0,5):" + str.substring(0, 5))
println(str + " hello!!")
println(str.replace("world", "Pay"))
for (i in str.toUpperCase()) {
print(i)
}
println()
println("----------------------------")
println("str[0]:" + str[0])
println("str.first():" + str.first())
println("str.last():" + str.last())
println("str[str.length-1]:" + str[str.length - 1])
println("----------判空-------------")
println("\"\".isEmpty():" + "".isEmpty())
println("\" \".isEmpty():" + " ".isEmpty())
println("\" \".isBlank():" + " ".isBlank())
println("abcdefg".filter { c -> c in 'a'..'d' })
}
str.length:12
str.substring(0,5):hello
hello world! hello!!
hello Pay!
HELLO WORLD!
----------------------------
str[0]:h
str.first():h
str.last():!
str[str.length-1]:!
----------判空-------------
"".isEmpty():true
" ".isEmpty():false
" ".isBlank():true
abcd
Kotlin支持原生字符串
用3个引号定义的字符串,最终打印的格式与代码中显示的格式一致,而不会解释转化转义的字符,以及Unicode的转义字符。
var payStr = """\n hello kotlin \n hello world"""
println(payStr)
\n hello kotlin \n hello world
例:
用字符串描述一段html代码。
使用普通字符串定义
val payHtml = "<html>\n" +
" <body>\n" +
" <p>Hello World.</p>\n" +
" </body>\n" +
"</html>\n"
println(payHtml)
<html>
<body>
<p>Hello World.</p>
</body>
</html>
采用原生字符串的方式
val payHtml2 = """<html>
<body>
<p>Hello World.</p>
</body>
</html>"""
println(payHtml2)
<html>
<body>
<p>Hello World.</p>
</body>
</html>
字符串模版
fun payMessage(name: String, lang: String) = "Hi $name, welcome to $lang"
println(payMessage("ZY", "Kotlin"))
Hi ZY, welcome to Kotlin
可以将表达式 通过字符串模版的方式插入到字符串中,并在${expression}中使用双引号。
println("Kotlin has ${if ("kotlin".length > 0) "kotlin".length else "no"}")
Kotlin has 6
字符串判等
内容相等。通过操作符==来判断两个对象的内容是否相等。
引用相等。通过操作符===来判断两个对象的引用是否一样,与之相反的判断操作符是!==。如果比较的是基础类型,比如Int,那么===的效果与==相同。
var a = "Java"
var b = "Java"
var c = "Kotlin"
var d = "Kot"
var e = "lin"
var f = d + e
println("a==b:" + (a == b))
println("a===b:" + (a === b))
println("c==f:" + (c == f))
println("c===f:" + (c === f))
a==b:true
a===b:true
c==f:true
c===f:false
参考Koltin核心编程