<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                ## 字符串常見操作 [TOC] 【Kotlin相比于Java,在字符串的處理上做了一些增強】,我們單獨來說說字符串這種數據類型。 ### **字符串轉換** Kotlin 標準庫提供了一套相似的擴展方法,用來把字符串轉換成基本數據類型( toInt 、toByte、toBoolean等): ``` println ("42". toInt() ) ``` 如圖所示 ![](https://box.kancloud.cn/347ca2de6e8e5ce0544c60f6b94ed767_504x625.png) 每個這樣的函數都會嘗試把字符串的內容解析成對應的類型,如果解析失敗則拋出NumberFormatException 。 ### **字符串查找** 在Kotlin中,為了方便字符串的查找,提供了多個函數,如first()、last()、get(index),分別用于查找字符串中的第1個元素、最后1個元素以及角標為index的元素。 ``` fun main(args: Array<String>) { var str = "Hello World!" println(str.first()) //獲取第1個元素 println(str.last()) //獲取最后1個元素 println(str.get(4)) //獲取第4個元素 println(str[4]) //獲取第4個元素 println(str.indexOf('o')) //查找字符串在原字符串中第1次出現的角標 println(str.lastIndexOf( 'o'))//查找字符串在原字符串中最后1次出現的角標 } ``` 運行結果 ``` H ! o o 4 7 ``` ### **遍歷** **Kotlin里面的字符串支持遍歷**,遍歷轉換成一個個的Char類型。參考代碼: ~~~ fun main(args: Array<String>) { var str: String = "黑馬程序員"; for (c in str) { println(c) } } ~~~ 輸出結果 ``` 黑 馬 程 序 員 Process finished with exit code 0 ``` ### **字符串替換** 在Kotlin中,除了可以使用Java中的replace()函數實現字符串的替換之外,還可以使用replaceFirst()、replaceAfter()、replaceBefore()等函數用于字符串的替換。 ![](https://img.kancloud.cn/13/ee/13ee17b4b54b9ffced67b25cd01b966f_1374x502.png) ``` fun main(args: Array<String>) { var str = "Hello World! Hello World!" println(str.replace("World", "Kotlin")) println(str.replaceFirst("World", "Kotlin")) println(str.replaceBefore("!", "Kotlin")) println(str.replaceAfter("Hello ", "Kotlin!")) } ``` 運行結果 ``` Hello Kotlin! Hello Kotlin! Hello Kotlin! Hello World! Kotlin! Hello World! Hello Kotlin! ``` ### **分割和正則支持:split、toRegex** 再說說字符串分割,同Java,**Kotlin字符串分割也是使用split函數,但是split使用上有些需要注意的**。 split函數源碼出自包——[kotlin.text.split](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-split.html?lang=en) ![](https://i.loli.net/2019/04/18/5cb89ca55ad46.jpg) 我們先回顧下Java里面的字符串分割函數的使用,參考代碼 ~~~ class TestDemo { public static void main(String[] args) { //字符串 String string = "hello.kotlin.heima"; String[] split = string.split("."); for (String s : split) { System.out.println("s:" + s); } } } ~~~ 運行結果 ``` Process finished with exit code 0 ``` 針對以上代碼,執行結果是什么呢?是的,看不到任何拆分效果,因為,**Java里面的split函數傳入的實參,會被默認當做正則表達式**,類似的代碼,我們放到Kotlin中,參考代碼: ~~~ fun main(args: Array<String>) { val string = "hello.kotlin.heima" val split = string.split(".") for (s in split) { System.out.println("s:" + s) } } ~~~ 運行結果 ``` s:hello s:kotlin s:heima Process finished with exit code 0 ``` 針對以上代碼,我們看到,字符串拆分成功了。說明**Kotlin中split函數,默認不會把傳入的參數當做正則表達式**。那**如果我就是想把傳入的參數當做正則表達式呢?怎么辦呢?可以通過toRegex方法**,參考代碼: ~~~ fun main(args: Array<String>) { println("hello.kotlin.heima".split("\\.".toRegex())) } ~~~ 運行結果 ``` [hello, kotlin, heima] ``` 除此之外,**Kotlin的split方法還允許傳入多個拆分符**,參考代碼: ~~~ fun main(args: Array<String>) { val string = "hello.kotlin.heima" val split = string.split(".") for (s in split) { println("s:" + s) } println("hello.kotlin.heima".split("\\.".toRegex())) println("hello.kotlin-itheima".split(".", "-"))//傳入2個分隔符 } ~~~ 運行結果 ``` s:hello s:kotlin s:heima [hello, kotlin, heima] [hello, kotlin, itheima] Process finished with exit code 0 ``` ### **截取:[substring](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-substring.html?lang=en)、[substringBeforeLast](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-substring-before-last.html?lang=en)、[substringAfterLast](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-substring-after-last.html?lang=en)** 什么是**字符串截取**?也就是**一個字符串取其中的一部分**。 在java里面字符串截取使用subString方法,**Kotlin同樣提供了subString方法。但是,除了subString方法,Kotlin還提供了其他靈活的截圖方法** ![](https://img.kancloud.cn/f4/58/f4588cdda4377971af5f85c125e585af_1029x451.png) ![](https://img.kancloud.cn/89/16/89163d4d3833fe9d6e951cbfaec58f9f_1399x494.png) 方法比較多,我們就挑幾個方給大家演示演示,參考代碼: ~~~ fun main(args: Array<String>) { val str = "hello kotlin" println("subString演示:${str.substring(0, 5)}") val path = "c:/基礎語法/字符串分裂.kt" //獲取文件目錄 println("${path.substringBeforeLast("/")}") //獲取文件全名(帶后綴) println("${path.substringAfterLast("/")}") val fileName = "字符串分裂.kt" //獲取文件名 println("${fileName.substringBeforeLast(".")}") //獲取文件拓展名 println("${fileName.substringAfterLast(".")}") } ~~~ 運行結果 ``` subString演示:hello c:/基礎語法 字符串分裂.kt 字符串分裂 kt ``` >[info]PS: substringBeforeLast:返回分隔符最后一次出現之前的子字符串。如果字符串不包含分隔符, 則返回默認為原始字符串的 Missingham長期以來值。 substringAfterLast:返回在最后一次出現分隔符后的之后的子字符串。如果字符串不包含分隔符, 則返回默認為原始字符串的 Missingham長期以來值。 ### **去空格** 去除字符串前后的空格在開發過程中是一個常見的需求。Java中通過trim方法去掉字符串空格,Kotlin中同樣提供了trim方法,作用同Java。除此之外,在 package kotlin.text 下面的Strings.kt和代碼Indent.kt代碼中還有trimStart、trimEnd、trimMargin(去除前導空格)、trimIndent(縮進字符串)等方法。我們先看trim、trimStart、trimEnd三個方法, * [trim](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-trim.html?lang=en):去除字符串前后空格 * [trimStart](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-trim-start.html?lang=en):去除字符串前面的空格 * [trimEnd](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-trim-end.html?lang=en):去除字符串后面的空格 參考代碼: ~~~ fun main(args: Array<String>) { println("${" 內容 ".trim()}") println("${" 內容 ".trimStart()}") println("${" 內容 ".trimEnd()}") } ~~~ 運行結果 ``` 內容 內容 內容 Process finished with exit code 0 ``` 另外,在 package kotlin.text 下面的Indent.kt代碼中,Kotlin還定義了 String 類的擴展函數: ``` fun String.trimMargin(marginPrefix: String = "|"): String fun String.trimIndent(): String ``` Indent.kt的屬性結構圖 ![](https://box.kancloud.cn/51fc8a6ccf7254e79935488604c57aa6_602x220.png) 我們再看[trimMargin](https://www.w3cschool.cn/doc_kotlin/kotlin-api-latest-jvm-stdlib-kotlin-text-trim-margin.html?lang=en),trimMargin可以去掉前導空格。什么是前導空格呢?也就是每行前面的空格,參考代碼: ~~~ fun main(args: Array<String>) { var str = """ |內容 |內容 |內容 |內容 """.trimMargin() println(str.trimMargin("|")) } ~~~ 運行結果 ``` 內容 |內容 內容 內容 Process finished with exit code 0 ``` * trimMargin() 函數默認使用 "|" 來作為邊界字符:但你可以選擇其他字符并作為參數傳入,比如 trimMargin(">") 。 * trimIndent() 函數,則是把字符串行的左邊空白對齊切割: ``` fun main(args: Array<String>) { //縮進字符串 val text=""" ABC 123 456""" println(text.trimIndent()) } ``` 運行結果 ``` ABC 123 456 Process finished with exit code 0 ``` ### 字符串字面值 字符串的字面值是一串字符常量,字符串字面值常量是用雙引號括起來""的零個或多個字符,如“hello”。Kotlin中有兩種類型的字符串字面值,一種是轉義字符串,可以包含轉義字符,另一種是原生字符串,可以包含轉義字符、換行和任意文本。 #### 轉義字符串 轉義是采用傳統的反斜杠“\”方式將字符進行轉義。Kotlin中的轉義字符串與Java中的轉義字符串類似,字符串在輸出時,如果想要輸出一些特殊字符,則需要用到轉義字符串,比如\t,\b,\n,\r,\',\",\\和\$。在這里以\n(換行符)為例,具體代碼如下所示 ``` fun main(args: Array<String>) { //字符串中包含轉義字符 val str = "您\n好" println(str) } ``` 運行結果 ``` 您 好 ``` 從運行結果可以看出,轉義字符串在輸出時,并不是保持字符串中原有內容輸出,而是輸出轉義后的內容。 * [ ] 引申:**反斜杠(\)** 反斜杠(\)是一個特殊的字符,被稱為轉義字符,它的作用是用來轉義后面的一個字符。轉義后的字符通常用于表示一個不可見的字符或具有特殊含義的字符,例如換行(\n)。下面列出一些常見的轉義字符。 * \r:表示回車符,將光標定位到當前行的開頭,不會跳到下一行。 * \n:表示換行符,換到下一行開頭。 * \t:表示制表符,將光標移動到下一個制表符的位置,類似在文檔中用Tab鍵的效果。 * \b:表示退格符號,類似鍵盤上的Backspace鍵。 * \':表示單引號字符,在Kotlin代碼中單引號表示字符的開始和結束,如果直接寫單引號字符('),程序會認為前兩個是一對,會報錯,因此需要使用轉義字符(\')。 * \":表示雙引號字符,Kotlin中雙引號表示字符串的開始和結束,包含在字符串中的雙引號需要轉義,比如""。 * \\:表示反斜杠字符,由于在Kotlin代碼中的反斜杠(\)是轉義字符,因此需要表示字面意義上的\,就需要使用雙反斜杠(\\)。 #### **三重引號** 字符串輸出的時候,想要輸出一些特殊字符,需要用到轉義字符串,比如\\t,\\b,\\n,\\r。轉義字符串,在Kotlin里面也是支持的。 Kotlin還新增了一種做法,字符串可以由三重引號(”””)分割,可以直接包含任意的特殊字符,參考代碼: ~~~ fun main(args: Array<String>) { //單行字符串使用轉義字符 var str1 = "ccc\n aaa"//通過轉義字符換行 println(str1) //三引號"""包起來的字符串,支持多行 val str2 = """ 多行字符串 多行字符串 """ println(str2) } ~~~ 運行結果 ``` ccc aaa 多行字符串 多行字符串 Process finished with exit code 0 ```
                  <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>

                              哎呀哎呀视频在线观看