5.字符串
                定义字符串
和Java类似,Kotlin支持直接通过字面量为一个字符串类型赋值
1  | val str="hello world"  | 
字符串操作
Kotlin支持一系列Java时代就有的熟悉操作
str.lengthstr.substring(0,5)str+"hello kotlin!"str.replace("world","kotlin")
此外,也提供了一些额外的API
- 字符串遍历:
for(c in str.toUpperCase()) - 字符串访问
str[0]str.first()str.last()str[str.length-1]
 - 字符串判断
str.isEmpty()str.isBlank()str.filter{c -> c in 'a'..'d'}str.filter{it in 'a'..'d'})
 
多行字符串
在传统写法中,我们需要通过\n来实现多行字符串,但是在代码中也仍然是单行的
1  | val html="<html>\n"+  | 
在Kotlin中支持如下的多行字符串写法
1  | val html="""<html>  | 
字符串模板
在传统写法中,为了在字符串中插入变量,我们不得不使用字符串拼接来实现
1  | val str="hi"+name+" welcome to"+place  | 
Kotlin支持字符串模板来提升字符串的紧凑型和可读性
1  | val str="hi ${name} welcome to ${place}”  | 
        Comments