網站首頁 編程語言 正文
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
相關推薦
- 2022-06-10 C#關鍵字Check簡單介紹_C#教程
- 2022-07-01 c++超細致講解引用_C 語言
- 2023-01-02 Python中字符串的常用方法總結_python
- 2022-04-01 k8s ip地址變了 報錯Error getting node“ err=“node \“maste
- 2022-10-15 Qt?TCP網絡通信學習_C 語言
- 2022-02-24 使用Nginx和Lua進行JWT校驗介紹_nginx
- 2022-11-24 redis使用skiplist跳表的原因解析_Redis
- 2022-02-13 QT 控件 QListWidget 設置所有事件都激發編輯(雙擊, 選擇, 選項變化)
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支