字符串还是有意思啊,跟Python中的操作还是比较相似的。本文的参考文献是《Kotlin从基础到实战》。
1_字符串的简单操作
1.1_查找
str.first()str.last()str.get(index)
var str = "Hello World"
str.first()
str.last()
str.get(3)
str[3]
str.indexOf('o')
// 找字符串在原字符串中第一次出现的角标
str.lastIndexOf('o')
// 找字符串在原字符串中最后1次出现的角标
1.2_截取
str.substring(3,7)str.substring(IntRange(3,7))str.subSequence(3,7)str.subSequence(IntRange(3,7))
1.3_替换
-
str.replace(old,new,ignoreCase=false) -
str.replaceFirst(old,new) -
str.replaceBefore(target,new)将满足条件的第一个字符串之前的所有字符串替换为new -
str.replaceAfter(target,new)将满足条件的第一个字符串之后的所有字符串替换为new
var str = "Hello World!Hello World!"
str.replaceBefore("!","Kotlin")
// "Kotlin!Hello World!"
str.replaceAfter("Hello ","Kotlin")
// "Hello Kotlin!"
1.4_分隔
str.split()
val str = "Hello.Kotlin/world"
var spl = str.split(".","/")
// [hello,kotlin,world]
1.5_去空格
str.trim()去前面的空格str.trimEnd()去后面的空格
var str = " Hello World "
str.trim() // "Hello World "
str.trimEnd() // " Hello World"
2_模板表达式
模板表达式就是在字符串中添加占位符,字符串模板表达式由${变量名/函数/表达式}组成,也可以省略{},例如$变量名。
var a = 1
var s1 = "a is $a"
var s2 = "a is ${a}"
var str = "a is 1"
var str1 = "${s2.replace("is","was")}"
var str2 = "${$}8.88"