日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Kotlin基礎通關之字符串與數字類型_Android

作者:niuyongzhi ? 更新時間: 2022-10-22 編程語言

1.kotlin的字符串操作和Java有些不同,有些新增。

1)先看字符串比較

java中==比較的是變量的引用是否指向同一個地址,Kotlin中用===比較引用。

kotlin中用==比較兩個字符串的內容是否一樣,相當于java中的equls。

    val str = "abc"
    val str2 = StringBuffer("abc").toString()
    println(str.equals(str2))//true
    println(str == str2)//true
    println(str === str2)//false

2)substring:字符串截取

Kotlin中substring支持IntRange類型(一個整數范圍)的參數。

    val hello = "Hello world!"
    val sub = hello.substring(0 until 5)
    val sub2 = hello.substring(0, 5)
    println(sub)//hello
    println(sub2)//hello

3)split 字符串分割

split 函數返回的是一個List集合,而List集合又支持解構語法特性,允許在一個表達式里給多個變量賦值,解構常用來簡化給變量的賦值。

    val names = "XiaoHua,HanMei,LiLei"
    val data:List<String> = names.split(",")
    val(first:String,second:String,third:String) = names.split(",")
    for(item in data){
        print(item)
    }
    println("$first $second $third")

4)replace 字符串替換

replace 可以接收一個正則表達式Regex,和一個lambda。

看一下replace函數的定義:

replace(regex: Regex, noinline transform: (MatchResult) -> CharSequence): String

當lambda是最有一個參數時,包括它的那對圓括號可以省略。看到下面的寫法不要陌生,前面講過,這個lambda是replace的一個參數。

   val hello = "Hello World!"
    val h2 = hello.replace(Regex("o")) {
        when (it.value) {
            "o" -> "0"
            else -> it.value
        }
    }
    println(h2)

5)forEach 字符串遍歷

當匿名函數只有一個參數時,可以用it關鍵字來表示參數。

看下forEach的定義:接收一個函數參數,函數的參數類型是Char,返回值是Unit,forEach的返回類型也是Unti

forEach(action: (Char) -> Unit): Unit

    val hello = "Hello World!"
    hello.forEach { char->
        println(char)
    }
    hello.forEach {
        println(it)
    }

2.數字類型

1)安全轉換函數,Kotlin提供了toDoubleOrNull和toIntOrNull這樣的安全轉換函數,如果數值不能正確轉換,不會拋出異常.NumberFormatException,而是返回null。

但是在java中,就會以異常的形式拋出。這樣就會提供所編寫程序的健壯性。

    val pi = "3.14"
    //這種發生就會拋出異常NumberFormatException
    val num = pi.toInt()
    //這個返回null
    val num2 = pi.toIntOrNull()
    println(num2)

2)Double類型數字格式化

"%.2f" 保留兩位小數。

    val pi = "%.2f".format(3.1415926)
    println(pi)

3)Double轉Int

    //損失精度
    println(3.5415.toInt())
    //四舍五入
    println(3.5415.roundToInt())

原文鏈接:https://blog.csdn.net/niuyongzhi/article/details/126523928

欄目分類
最近更新