<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Kotlin 字符串 > 原文: [http://zetcode.com/kotlin/strings/](http://zetcode.com/kotlin/strings/) Kotlin 字符串教程展示了如何在 Kotlin 中使用字符串。 字符串是編程語言中的基本數據類型。 在 Kotlin 中,`String`類表示字符串。 Kotlin 字符串字面值被實現為此類的實例。 Kotlin 使用雙引號創建字符串字面值。 Kotlin 具有用于處理字符串的豐富 API。 它包含許多用于各種字符串操作的方法。 Kotlin/Java 字符串是不可變的,這意味著所有修改操作都會創建新的字符串,而不是就地修改字符串。 ## Kotlin 字符串示例 在第一個示例中,我們有一個簡單的 Kotlin 字符串示例。 `KotlinStringBasic.kt` ```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") } ``` 該示例創建一個字符串,使用字符串連接操作,并確定該字符串的寬度。 ```kt val s = "Today is a sunny day." println(s) ``` 將創建一個字符串字面值并將其傳遞給`s`變量。 使用`println()`將字符串打印到控制臺。 ```kt println("Old " + "bear") ``` 在 Kotlin 中,字符串與`+`運算符連接在一起。 ```kt println("The string has " + s.length + " characters") ``` 字符串的長度由`length`屬性確定。 ```kt Today is a sunny day. Old bear The string has 21 characters ``` 這是輸出。 ## Kotlin 字符串索引 字符串是字符序列。 我們可以通過索引操作從字符串中獲取特定字符。 `KotlinStringIndexes.kt` ```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()) } ``` 該示例顯示了如何獲取字符串的第一個和最后一個字符。 它使用索引操作和替代的字符串方法。 ```kt println(s[0]) println(s[s.length-1]) ``` 索引從零開始; 因此,第一個字符的索引為零。 字符的索引放在方括號之間。 ```kt println(s.first()) println(s.last()) ``` `first()`方法返回字符串的第一個字符,`last()`返回字符串的最后一個字符。 ## Kotlin 字符串插值 字符串插值是變量替換,其值在字符串中。 在 Kotlin 中,我們使用`$`字符插入變量,并使用`${}`插入表達式。 Kotlin 字符串格式化比基本插值功能更強大。 `KotlinStringInterpolate.kt` ```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 中進行字符串插值。 ```kt val name = "Peter" val age = 34 ``` 我們有兩個變量。 ```kt println("$name is $age years old") ``` 這兩個變量在字符串內插; 即用它們的值替換它們。 ```kt println("The string has ${msg.length} characters") ``` 在這里,我們得到字符串的長度。 由于它是一個表達式,因此需要將其放在`{}`括號內。 ```kt Peter is 34 years old The string has 20 characters ``` 這是輸出。 ## Kotlin 字符串比較 我們可以使用`==`運算符和`compareTo()`方法來比較字符串內容。 `KotlinCompareStrings.kt` ```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") } } ``` 在示例中,我們比較兩個字符串。 ```kt if (s1 == s2) { ``` `==`運算符比較結構相等性,即兩個字符串的內容。 ```kt val res = s1.compareTo(s2, true) ``` `compareTo()`方法按字典順序比較兩個字符串,可以忽略大小寫。 ## Kotlin 字符串轉義字符 字符串轉義字符是執行特定操作的特殊字符。 例如,`\n`字符開始換行。 `KotlinStringEscapeCharacters.kt` ```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 中的轉義字符。 ```kt println("He said: \"I love ice skating\"") ``` 我們通過轉義雙引號的原始功能,將雙引號插入字符串字面值中。 ```kt println("Line 1:\nLine 2:\nLine 3:") ``` 使用`\n`,我們創建了三行。 ```kt Three bottles of wine He said: "I love ice skating" Line 1: Line 2: Line 3: ``` 這是輸出。 ## Kotlin 字符串大小寫 Kotlin 具有處理字符串字符大小寫的方法。 `KotlinStringCase.kt` ```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()`。 ```kt Young eagle YOUNG EAGLE young eagle hornet ``` 這是示例的輸出。 ## Kotlin 空/空白字符串 Kotlin 區分空字符串和空字符串。 空字符串不包含任何字符,空白字符串包含任意數量的空格。 `KotlinStringEmptyBlank.kt` ```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") } } ``` 該示例測試字符串是否平淡且為空。 ```kt if (s.isEmpty()) { ``` 如果字符串為空,則`isEmpty()`返回`true`。 ```kt if (s.isBlank()) { ``` 如果字符串為空白,則`isBlank()`返回`true`。 ```kt The string is not empty The string is blank ``` 這是示例的輸出。 ## Kotlin 字符串空格去除 我們經常需要從字符串中去除空格字符。 `KotlinStringSort.kt` ```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") } ``` 該示例介紹了從字符串中去除空格的方法。 ```kt val s1 = s.trimEnd() ``` `trimEnd()`方法刪除尾隨空格。 ```kt val s2 = s.trimStart() ``` `trimStart()`方法刪除前導空格。 ```kt val s3 = s.trim() ``` `trim()`方法同時刪除尾隨空格和前導空格。 ## Kotlin 字符串循環 Kotlin 字符串是字符序列。 我們可以循環執行此序列。 `KotlinStringLoop.kt` ```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`循環遍歷字符串。 ```kt for (e in phrase) { print("$e ") } ``` 我們使用`for`循環遍歷字符串并打印每個字符。 ```kt phrase.forEach { e -> print(String.format("%#x ", e.toByte())) } ``` 我們使用`forEach`遍歷一個循環,并打印每個字符的字節值。 ```kt phrase.forEachIndexed { idx, e -> println("phrase[$idx]=$e ") } ``` 使用`forEachIndexed`,我們將打印帶有索引的字符。 ```kt 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` ```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") } ``` 該示例計算字符串中的所有元音。 ```kt fun Char.isEnglishVowel(): Boolean = this.toLowerCase() == 'a' || this.toLowerCase() == 'e' || this.toLowerCase() == 'i' || this.toLowerCase() == 'o' || this.toLowerCase() == 'u' || this.toLowerCase() == 'y' ``` 我們創建一個擴展函數; 對于英語元音,它返回`true`。 ```kt val res = s.filter { e -> e.isEnglishVowel()} ``` 擴展函數在`filter()`方法中調用。 ## Kotlin 字符串 `startsWith`/`endsWith` 如果字符串以指定的前綴開頭,則`startsWith()`方法返回`true`;如果字符串以指定的字符結尾,則`endsWith()`返回`true`。 `KotlinStringStartEnd.kt` ```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"`開頭。 ```kt val words = listOf("tank", "boy", "tourist", "ten", "pen", "car", "marble", "sonnet", "pleasant", "ink", "atom") ``` 使用`listOf()`,我們定義了一個單詞列表。 ```kt val res = words.filter { e -> startWithT(e) } println(res) val res2 = words.filter { e -> endWithK(e) } println(res2) ``` 我們在`filter()`方法中調用了兩個自定義函數。 ```kt fun startWithT(word: String): Boolean { return word.startsWith("t") } ``` `startWithT()`是一個自定義謂詞函數,如果字符串以't'開頭,則返回`true`。 ```kt [tank, tourist, ten] [tank, ink] ``` 這是輸出。 ## Kotlin 字符串替換 `replace()`方法返回通過將所有出現的舊字符串替換為新字符串而獲得的新字符串。 `KotlinStringReplace.kt` ```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` ```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) } } ``` 該示例創建一個城市對象列表。 我們遍歷列表并將對象打印到控制臺。 ```kt override fun toString(): String { return "$name has population $population" } ``` 我們將覆蓋`toString()`的默認實現。 它返回一個字符串,表明一個城市具有指定的人口。 ```kt Bratislava has population 432000 Budapest has population 1759000 Prague has population 1280000 ``` 這是輸出。 ## Kotlin 原始字符串 原始字符串由三引號`"""`分隔。它沒有轉義,并且可以包含換行符和任何其他字符。 `KotlinRawString.kt` ```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` ```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()`將數字用點字符填充。 ```kt .................657 .................122 ................3245 .................345 ..................99 ..................18 ``` 這是輸出。 在本教程中,我們介紹了 Kotlin 字符串。 您可能也對相關教程感興趣: [Kotlin 列表教程](/kotlin/lists/), [Kotlin Hello World 教程](/kotlin/helloworld/), [Kotlin 變量教程](/kotlin/variables/), [Kotlin 控制流](/kotlin/controlflow/) , [Kotlin 讀取文件教程](/kotlin/readfile/)和 [Kotlin 寫入文件教程](/kotlin/writefile/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看