跳转至

Kotlin 字符串

原文: http://zetcode.com/kotlin/strings/

Kotlin 字符串教程展示了如何在 Kotlin 中使用字符串。

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

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

Kotlin 字符串示例

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

KotlinStringBasic.kt

package com.zetcode

fun main(args: Array<String>) {

    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 字符串索引

字符串是字符序列。 我们可以通过索引操作从字符串中获取特定字符。

KotlinStringIndexes.kt

package com.zetcode

fun main(args: Array<String>) {

    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 字符串格式化比基本插值功能更强大。

KotlinStringInterpolate.kt

package com.zetcode

fun main(args: Array<String>) {

    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()方法来比较字符串内容。

KotlinCompareStrings.kt

package com.zetcode

fun main(args: Array<String>) {

    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字符开始换行。

KotlinStringEscapeCharacters.kt

package com.zetcode

fun main(args: Array<String>) {

    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 具有处理字符串字符大小写的方法。

KotlinStringCase.kt

package com.zetcode

fun main(args: Array<String>) {

    val s = "young eagle"

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

    println("Hornet".decapitalize())
}

该示例提出了四种方法:capitalize()toUpperCase()toLowerCase()decapitalize()

Young eagle
YOUNG EAGLE
young eagle
hornet

这是示例的输出。

Kotlin 空/空白字符串

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

KotlinStringEmptyBlank.kt

package com.zetcode

fun main(args: Array<String>) {

    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 字符串空格去除

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

KotlinStringSort.kt

package com.zetcode

fun main(args: Array<String>) {

    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 字符串是字符序列。 我们可以循环执行此序列。

KotlinStringLoop.kt

package com.zetcode

fun main(args: Array<String>) {

    val phrase = "young eagle"

    for (e in phrase) {

        print("$e ")
    }

    println()

    phrase.forEach { e -> print(String.format("%#x ", 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(String.format("%#x ", 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(args: Array<String>) {

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

fun main(args: Array<String>) {

    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(args: Array<String>) {

    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(args: Array<String>) {

    val s = "Today is a sunny day."

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

该示例用多雨代替晴天。 返回一个新的修改后的字符串。 原始字符串未修改。

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(args: Array<String>) {

    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(args: Array<String>) {

    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 具有将字符串填充到指定字符或空格的方法。

KotlinStringPad.kt

package com.zetcode

fun main(args: Array<String>) {

    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 列表教程Kotlin Hello World 教程Kotlin 变量教程Kotlin 控制流Kotlin 读取文件教程Kotlin 写入文件教程


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组