ZetCode

Kotlin 字符串

最后修改于 2024 年 1 月 29 日

在本文中,我们将展示如何在 Kotlin 中使用字符串。

字符串是编程语言中的一种基本数据类型。在 Kotlin 中,String 类表示字符串。 Kotlin 字符串字面量被实现为该类的实例。 Kotlin 使用双引号创建字符串字面量。

Kotlin 拥有丰富的 API 来处理字符串。它包含许多用于各种字符串操作的方法。 Kotlin/Java 字符串是不可变的,这意味着所有修改操作都会创建新的字符串,而不是就地修改字符串。

Kotlin 字符串示例

在第一个示例中,我们有一个简单的 Kotlin 字符串示例。

StringBasic.kt
package com.zetcode

fun main() {

    val s = "Today is a sunny day."
    println(s)

    println("Old " + "bear")

    println("The string has " + s.length + " characters")
}

该示例创建一个字符串,使用字符串连接操作,并确定字符串的宽度。

val s = "Today is a sunny day."
println(s)

创建一个字符串字面量并将其传递给 s 变量。使用 println 将字符串打印到控制台。

println("Old " + "bear")

在 Kotlin 中,字符串使用 + 运算符连接。

println("The string has " + s.length + " characters")

字符串的长度由 length 属性确定。

Today is a sunny day.
Old bear
The string has 21 characters

Kotlin 字符串长度

对于许多字母表,length 属性给出了正确的字符数。

StringLength.kt
package com.zetcode

import java.text.BreakIterator

fun main() {

    val word = "falcon"
    println(word.length)

    val word2 = "čerešňa"
    println(word2.length)

    val word3 = "ведомство"
    println(word3.length)

    val word4 = "合気道"
    println(word4.length)
}

在示例中,我们打印英语、斯洛伐克语、俄语和日语单词的字符数。

6
7
9
3

输出是正确的。


但是,有些字母表,length 属性会给出不正确的输出。

StringLength2.kt
package com.zetcode

import java.text.BreakIterator

fun main() {

    val emojis = "🐜🐬🐄🐘🦂🐫🐑🦍🐯🐞"
    println(emojis.length)

    val it = BreakIterator.getCharacterInstance()
    it.setText(emojis)
    var count = 0

    while (it.next() != BreakIterator.DONE) {
        count++
    }

    println(count)

    println("--------------------------")

    val word = "नमस्ते"
    println(word.length)

    val it2 = BreakIterator.getCharacterInstance()
    it2.setText(word)
    var count2 = 0

    while (it2.next() != BreakIterator.DONE) {
        count2++
    }

    println(count2)
}

例如,对于表情符号和梵文单词,length 属性会给出错误的数字。我们可以使用 BreakIterator 获得表情符号的正确答案。但是,对于梵文单词,BreakIterator 仍然不正确。

20
10
--------------------------
6
3

有 10 个表情符号字符和 4 个梵文字符。

Kotlin 字符串索引

字符串是一个字符序列。我们可以使用索引操作从字符串中获取特定字符。

StringIndexes.kt
package com.zetcode

fun main() {

    val s = "blue sky"

    println(s[0])
    println(s[s.length-1])

    println(s.first())
    println(s.last())
}

该示例演示了如何获取字符串的第一个和最后一个字符。它使用索引操作和替代字符串方法。

println(s[0])
println(s[s.length-1])

索引从零开始;因此,第一个字符的索引为零。字符的索引放在方括号之间。

println(s.first())
println(s.last())

first 方法返回字符串的第一个字符,last 方法返回字符串的最后一个字符。

Kotlin 字符串插值

字符串插值是用其值替换字符串中的变量。在 Kotlin 中,我们使用 $ 字符来插值变量,使用 ${} 来插值表达式。

Kotlin 字符串格式化比基本插值更强大。

StringInterpolate.kt
package com.zetcode

fun main() {

    val name = "Peter"
    val age = 34

    println("$name is $age years old")

    val msg = "Today is a sunny day"

    println("The string has ${msg.length} characters")
}

该示例演示了如何在 Kotlin 中进行字符串插值。

val name = "Peter"
val age = 34

我们有两个变量。

println("$name is $age years old")

这两个变量在字符串中被插值;即,它们被替换为它们的值。

println("The string has ${msg.length} characters")

在这里,我们获取字符串的长度。由于它是一个表达式,我们需要将其放入 {} 括号内。

Peter is 34 years old
The string has 20 characters

Kotlin 比较字符串

我们可以使用 == 运算符和 compareTo 方法来比较字符串内容。

CompareStrings.kt
package com.zetcode

fun main() {

    val s1 = "Eagle"
    val s2 = "eagle"

    if (s1 == s2) {

        println("Strings are equal")
    }  else {

        println("Strings are not equal")
    }

    println("Ignoring case")

    val res = s1.compareTo(s2, true)

    if (res == 0) {

        println("Strings are equal")
    }  else {

        println("Strings are not equal")
    }
}

在示例中,我们比较两个字符串。

if (s1 == s2) {

== 运算符比较结构相等性,即两个字符串的内容。

val res = s1.compareTo(s2, true)

compareTo 方法按字典顺序比较两个字符串,可以选择忽略大小写。

Kotlin 字符串转义字符

字符串转义字符是执行特定操作的特殊字符。例如,\n 字符开始新的一行。

EscapeCharacters.kt
package com.zetcode

fun main() {

    println("Three\t bottles of wine")
    println("He said: \"I love ice skating\"")
    println("Line 1:\nLine 2:\nLine 3:")
}

该示例介绍了 Kotlin 中的字符转义。

println("He said: \"I love ice skating\"")

我们通过转义双引号的原始功能将双引号插入到字符串字面量中。

println("Line 1:\nLine 2:\nLine 3:")

使用 \n,我们创建了三行。

Three    bottles of wine
He said: "I love ice skating"
Line 1:
Line 2:
Line 3:

Kotlin 字符串大小写

Kotlin 具有用于处理字符串字符大小写的方法。

StringCase.kt
package com.zetcode

fun main() {

    val s = "young eagle"

    println(s.capitalize())
    println(s.toUpperCase())
    println(s.toLowerCase())

    println("Hornet".decapitalize())
}

该示例介绍了四种方法:capitalizetoUpperCasetoLowerCasedecapitalize

Young eagle
YOUNG EAGLE
young eagle
hornet

Kotlin 空/空白字符串

Kotlin 区分空字符串和空白字符串。空字符串没有任何字符,空白字符串包含任意数量的空格。

EmptyBlank.kt
package com.zetcode

fun main() {

    val s = "\t"

    if (s.isEmpty()) {

        println("The string is empty")
    } else {

        println("The string is not empty")
    }

    if (s.isBlank()) {

        println("The string is blank")
    } else {

        println("The string is not blank")
    }
}

该示例测试一个字符串是空白还是空的。

if (s.isEmpty()) {

如果字符串为空,则 isEmpty 返回 true。

if (s.isBlank()) {

如果字符串是空白,则 isBlank 返回 true。

The string is not empty
The string is blank

Kotlin 字符串去除空格

我们经常需要从字符串中去除空格字符。

StringTrim.kt
package com.zetcode

fun main() {

    val s = " Eagle\t"

    println("s has ${s.length} characters")

    val s1 = s.trimEnd()
    println("s1 has ${s1.length} characters")

    val s2 = s.trimStart()
    println("s2 has ${s2.length} characters")

    val s3 = s.trim()
    println("s2 has ${s3.length} characters")
}

该示例介绍了从字符串中去除空格的方法。

val s1 = s.trimEnd()

trimEnd 方法删除尾随空格。

val s2 = s.trimStart()

trimStart 方法删除前导空格。

val s3 = s.trim()

trim 方法删除尾随和前导空格。

Kotlin 字符串循环

Kotlin 字符串是一个字符序列。我们可以循环遍历这个序列。

StringLoop.kt
package com.zetcode

fun main() {

    val phrase = "young eagle"

    for (e in phrase) {

        print("$e ")
    }

    println()

    phrase.forEach { e -> print("%#x ".format(e.toByte())) }

    println()

    phrase.forEachIndexed { idx, e -> println("phrase[$idx]=$e ")  }
}

该示例使用 for 循环、forEach 循环和 forEachIndexed 循环遍历字符串。

for (e in phrase) {

    print("$e ")
}

我们使用 for 循环遍历字符串并打印每个字符。

phrase.forEach { e -> print("%#x ".format(e.toByte())) }

我们使用 forEach 循环遍历字符串并打印每个字符的字节值。

phrase.forEachIndexed { idx, e -> println("phrase[$idx]=$e ")  }

使用 forEachIndexed,我们打印带有其索引的字符。

y o u n g   e a g l e 
0x79 0x6f 0x75 0x6e 0x67 0x20 0x65 0x61 0x67 0x6c 0x65 
phrase[0]=y 
phrase[1]=o 
phrase[2]=u 
phrase[3]=n 
phrase[4]=g 
phrase[5]=  
phrase[6]=e 
phrase[7]=a 
phrase[8]=g 
phrase[9]=l 
phrase[10]=e 

Kotlin 字符串过滤

filter 方法返回一个字符串,该字符串仅包含与给定谓词匹配的原始字符串中的那些字符。

KotlinStringFilter.kt
package com.zetcode

fun main() {

fun Char.isEnglishVowel(): Boolean =  this.toLowerCase() == 'a'
        || this.toLowerCase() == 'e'
        || this.toLowerCase() == 'i'
        || this.toLowerCase() == 'o'
        || this.toLowerCase() == 'u'
        || this.toLowerCase() == 'y'

fun main() {

    val s = "Today is a sunny day."

    val res = s.filter { e -> e.isEnglishVowel()}

    println("There are ${res.length} vowels")
}

该示例计算字符串中的所有元音。

fun Char.isEnglishVowel(): Boolean =  this.toLowerCase() == 'a'
        || this.toLowerCase() == 'e'
        || this.toLowerCase() == 'i'
        || this.toLowerCase() == 'o'
        || this.toLowerCase() == 'u'
        || this.toLowerCase() == 'y'

我们创建一个扩展函数;它对英语元音返回 true。

val res = s.filter { e -> e.isEnglishVowel()}

扩展函数在 filter 方法中被调用。

Kotlin 字符串 startsWith/endsWith

如果字符串以指定的前缀开头,则 startsWith 方法返回 true,如果字符串以指定的字符结尾,则 endsWith 返回 true。

KotlinStringStartEnd.kt
package com.zetcode

fun main() {
    
    val words = listOf("tank", "boy", "tourist", "ten",
            "pen", "car", "marble", "sonnet", "pleasant",
            "ink", "atom")

    val res = words.filter { e -> startWithT(e) }
    println(res)

    val res2 = words.filter { e -> endWithK(e) }
    println(res2)
}

fun startWithT(word: String): Boolean {

    return word.startsWith("t")
}

fun endWithK(word: String): Boolean {

    return word.endsWith("k")
}

在示例中,我们有一个单词列表。使用上述方法,我们找出哪些单词以“t”开头,以“k”结尾。

val words = listOf("tank", "boy", "tourist", "ten",
        "pen", "car", "marble", "sonnet", "pleasant",
        "ink", "atom")

使用 listOf,我们定义一个单词列表。

val res = words.filter { e -> startWithT(e) }
println(res)

val res2 = words.filter { e -> endWithK(e) }
println(res2)

我们在 filter 方法中调用两个自定义函数。

fun startWithT(word: String): Boolean {

    return word.startsWith("t")
}

startWithT 是一个自定义谓词函数,如果字符串以“t”开头,则返回 true。

[tank, tourist, ten]
[tank, ink]

Kotlin 字符串替换

replace 方法返回一个新字符串,该字符串通过将旧字符串的所有匹配项替换为新字符串而获得。

KotlinStringReplace.kt
package com.zetcode

fun main() {

    val s = "Today is a sunny day."

    val w = s.replace("sunny", "rainy")
    println(w)
}

该示例将 sunny 替换为 rainy。返回一个新的修改后的字符串。原始字符串未被修改。

Kotlin 字符串分割

split 函数根据指定的分隔符将字符串分割成字符串列表。

KotlinSplit.kt
package com.zetcode

fun main() {

    val word = "eagle,falcon,hawk,owl"

    val birds = word.split(",")

    birds.forEach(::println)
}

我们有一个由逗号分隔的鸟组成的字符串。我们分割字符串以单独获取所有鸟类。

eagle
falcon
hawk
owl

Kotlin toString

当对象在字符串上下文中使用时(例如,打印到控制台),将调用 toString 方法。它的目的是提供对象的字符串表示形式。

KotlinToString.kt
package com.zetcode

class City(private var name: String, private var population: Int) {

    override fun toString(): String {
        return "$name has population $population"
    }
}

fun main() {

    val cities = listOf(City("Bratislava", 432000),
            City("Budapest", 1759000),
            City("Prague", 1280000))

    cities.forEach { e -> println(e) }
}

该示例创建了一个城市对象列表。我们遍历列表并将对象打印到控制台。

override fun toString(): String {
    return "$name has population $population"
}

我们覆盖了 toString 的默认实现。它返回一个字符串,说明一个城市具有指定的人口。

Bratislava has population 432000
Budapest has population 1759000
Prague has population 1280000

Kotlin 原始字符串

原始字符串用三引号 """ 分隔。它不进行转义,可以包含换行符和任何其他字符。

KotlinRawString.kt
package com.zetcode

fun main() {

    val sonnet = """
        Not marble, nor the gilded monuments
        Of princes, shall outlive this powerful rhyme;
        But you shall shine more bright in these contents
        Than unswept stone, besmear'd with sluttish time.
        When wasteful war shall statues overturn,
        And broils root out the work of masonry,
        Nor Mars his sword nor war's quick fire shall burn
        The living record of your memory.
        'Gainst death and all-oblivious enmity
        Shall you pace forth; your praise shall still find room
        Even in the eyes of all posterity
        That wear this world out to the ending doom.
        So, till the judgment that yourself arise,
        You live in this, and dwell in lovers' eyes.
        """

    println(sonnet.trimIndent())
}

在示例中,我们有一个多行字符串,其中包含一首诗。当打印字符串时,我们去除缩进。

Kotlin 字符串填充

Kotlin 有使用指定字符或空格填充字符串的方法。

StringPad.kt
package com.zetcode

fun main() {

    val nums = intArrayOf(657, 122, 3245, 345, 99, 18)

    nums.toList().forEach { e -> println(e.toString().padStart(20, '.')) }
}

该示例使用 padStart 用点字符填充数字。

.................657
.................122
................3245
.................345
..................99
..................18

来源

Kotlin 字符串 - 语言参考

在本文中,我们介绍了 Kotlin 字符串。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 Kotlin 教程