Kotlin字符串基础
外观
Kotlin字符串基础[编辑 | 编辑源代码]
字符串(String)是编程中最常用的数据类型之一,表示由字符组成的不可变序列。在Kotlin中,字符串是`String`类的实例,提供了丰富的操作方法和属性。
字符串的声明[编辑 | 编辑源代码]
Kotlin提供两种字符串声明方式:
转义字符串(Escaped Strings)[编辑 | 编辑源代码]
使用双引号声明,支持转义字符(如`\n`, `\t`等):
val simpleString = "Hello, Kotlin!\nThis is a new line."
println(simpleString)
输出:
Hello, Kotlin! This is a new line.
原始字符串(Raw Strings)[编辑 | 编辑源代码]
使用三重引号声明,保留所有格式(包括换行和缩进):
val rawString = """
This is a raw string:
* Line 1
* Line 2
Indentation is preserved!
""".trimIndent()
println(rawString)
输出:
This is a raw string: * Line 1 * Line 2 Indentation is preserved!
字符串模板[编辑 | 编辑源代码]
Kotlin支持字符串模板,允许在字符串中直接嵌入表达式:
val name = "Alice"
val age = 25
println("My name is $name and I'm ${age + 5} years old in 5 years")
输出:
My name is Alice and I'm 30 years old in 5 years
字符串常用操作[编辑 | 编辑源代码]
以下是Kotlin字符串的核心操作方法:
长度与空检查[编辑 | 编辑源代码]
val str = "Kotlin"
println("Length: ${str.length}") // 6
println("Is empty: ${str.isEmpty()}") // false
访问字符[编辑 | 编辑源代码]
可以通过索引或`get()`方法访问:
val str = "Android"
println(str[0]) // 'A'
println(str.get(3)) // 'r'
子字符串[编辑 | 编辑源代码]
val str = "Programming"
println(str.substring(3, 7)) // "gram"
println(str.dropLast(4)) // "Program"
字符串比较[编辑 | 编辑源代码]
Kotlin提供两种比较方式:
val a = "kotlin"
val b = "Kotlin"
println(a == b) // false (值比较)
println(a.equals(b)) // false
println(a.equals(b, true)) // true (忽略大小写)
字符串转换[编辑 | 编辑源代码]
常见转换操作示例:
val numStr = "123"
println(numStr.toInt()) // 123
val mixedCase = "KoTLiN"
println(mixedCase.toLowerCase()) // "kotlin"
println(mixedCase.toUpperCase()) // "KOTLIN"
字符串拼接[编辑 | 编辑源代码]
多种拼接方式对比:
val s1 = "Hello"
val s2 = "World"
// 方式1: +操作符
println(s1 + " " + s2) // "Hello World"
// 方式2: 字符串模板
println("$s1 $s2") // "Hello World"
// 方式3: joinToString
val list = listOf(s1, s2)
println(list.joinToString(" ")) // "Hello World"
实际应用案例[编辑 | 编辑源代码]
用户输入处理[编辑 | 编辑源代码]
fun processInput(input: String) {
when {
input.isBlank() -> println("Empty input")
input.length > 10 -> println("Too long (${input.length} chars)")
else -> println("Processing: ${input.trim()}")
}
}
processInput(" Hello ") // 输出: Processing: Hello
密码强度检查[编辑 | 编辑源代码]
fun checkPassword(password: String): String {
return when {
password.length < 6 -> "Weak"
password.any { it.isDigit() } &&
password.any { it.isLetter() } -> "Strong"
else -> "Medium"
}
}
println(checkPassword("abc123")) // 输出: Strong
性能考虑[编辑 | 编辑源代码]
Kotlin字符串是不可变的,频繁修改时应使用`StringBuilder`:
val builder = StringBuilder()
repeat(100) {
builder.append(it).append(", ")
}
println(builder.toString().removeSuffix(", "))
字符串与Unicode[编辑 | 编辑源代码]
Kotlin完全支持Unicode字符:
val emoji = "I ❤ Kotlin \uD83D\uDE00"
println(emoji) // 输出: I ❤ Kotlin 😀
总结[编辑 | 编辑源代码]
特性 | 说明 |
---|---|
不可变性 | 字符串创建后不可修改 |
双引号字符串 | 支持转义字符 |
三重引号字符串 | 保留原始格式 |
字符串模板 | 支持`$`表达式嵌入 |
丰富API | 提供100+实用方法 |
在数学表达式中,字符串长度公式表示为:,其中是字符数量。
页面模块:Message box/ambox.css没有内容。
避免在循环中使用`+`拼接字符串,这会导致性能问题。 |