当前位置:网站首页>Kotlin basic string operation, numeric type conversion and standard library functions
Kotlin basic string operation, numeric type conversion and standard library functions
2022-06-13 06:24:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
One . String manipulation
1.substring
String interception ,substring Function support IntRange type ( Represents the type of an integer range ) Parameters of ,until The range created does not include the upper limit value ( Not before, not after ).
const val NAMES="jack,xiao,jason"
fun main() {
// Not before the package
val substring = NAMES.substring(0 until 3)
println(substring)
}
2.split
split After the function is split, it returns a List aggregate , and List Collections also support deconstruction Syntax , It allows you to in an expression , Assign values to multiple variables at the same time , Deconstruction is often used to simplify variable assignment .
const val NAMES="jack,xiao,jason"
fun main() {
// By deconstructing grammar , Assign multiple variables at the same time
val (origin,dest,proxy) = NAMES.split(",")
println("$origin $dest $proxy")
}
3.replace
replace Function to replace the string , We can go with when Function collaboration
fun main() {
// Replace
val str1 = "United States of America"
// One parameter ,Regex Function is a regular expression ( Case sensitive ), Used to consciously replace those characters
// The second parameter is the anonymous function , We use the when Function to determine how to replace these characters
val str2 = str1.replace(Regex("[usoa]")) {
when (it.value) {
"a" -> "6"
"s" -> "8"
"o" -> "2"
"a" -> "9"
else -> it.value
}
}
println("$str1 \n")
println(str2)
}
4. String comparison
stay kotlin in , use == Check whether the characters in the two strings are the same , use === Check the alignment of two string variables
Like whether the address is the same .
fun main() {
//== Compare content === Compare memory addresses // The memory address is the same when comparing two values that are constant , Variables are different
val str3 ="XiaoHua"
// Copy
val str4=str3.capitalize()
println("$str3 $str4")
println(str3==str4)
println(str4===str3)
}
5.forEach
fun main() {
// Loop string
val str5="United States of America"
str5.forEach {
println("$it *")
}
}
Two . Digital type conversion
1. Safety conversion function
Kotlin Provides toDoubleOrNull and toIntNull Such a safe conversion function , If the value cannot be converted correctly , Rather than trigger an exception, return null value
fun main() {
// If the transfer is not successful, it will return null
val number:Int? ="8.89".toIntOrNull()
// If it is not converted, an error will be reported directly
// val number1:Int? ="8.89".toInt()
println(number)
println(number1)
}
2.Double turn In
fun main() {
// Omit after the decimal point
println(8.956756.toInt())
// rounding
println(8.956756.roundToInt())
}
3.Double Type formatting
A format string is a special set of characters , He will decide how to format the data
fun main() {
// Keep two decimal places , And turn it into a string
val format = "%.2f".format(8.956756)
println(format)
}
3、 ... and . Standard library functions
1.apply
apply Function can be regarded as a configuration function , You can pass in a recipient , Then call a series of functions to configure it to use , Provided lambda to apply Function execution , It will return to the configured receiver
fun main() {
// not used apply function
val file = File("E://i have a dream_copy.text")
file.setReadable(true)
file.setWritable(true)
file.setExecutable(false)
// Use apply function
// You can implicitly call the function in this object , And return the configured object
val apply = File("E://i have a dream_copy.text").apply {
setReadable(true)
setWritable(true)
setExecutable(false)
}
}
As mentioned above , When calling a function class to configure the receiver , The variable name is omitted , This is because , stay lambda Expression inside ,apply Can make every configuration function act on the receiver , This behavior is also called Related scope , because lambda All function calls in the expression are aimed at the receiver , Or implicit calls from their recipients .
2.let
let Function enables each variable to act on its lambda Expression inside , Give Way it Keywords can reference it .let And apply Compare ,
let Will send the recipient to lambda, and apply Pass nothing on , Anonymous function completed ,apply The current recipient will be returned ,
and let Returns the lambda Last line
fun main() {
//let It will return the value calculated in the function on the last line apply You can only return the current calling object and make an implicit call
// Use let Send out
val result = listOf(3, 2, 1).first().let {
it * it
}
print(result)
// Don't use let How to write it
val first = listOf(3, 2, 1).first()
print(first*first)
}
3.run
run and apply Can also be called implicitly in the scope , But also with apply Different ,run When the function returns lambda result , meanwhile run Function references can also be executed
fun main() {
//run and apply Similarly, you can implicitly call But will return lambda result
val run1 = "The people' s Republic of China".run {
"$length ,$this"
}
println(run1)
//run It can also be used to execute function references
// double :: And reference is a function such as this and new Out object
val run = "The people' s Republic of China".run(::isLong).run (::println)
}
fun isLong(name :String) =name.length>=10
4.With
with Function time run A variation of the , Their function is the same , but with Is called in different ways , call with The need when The value parameter is passed in as its first parameter
fun main() {
//with and run The same is the difference between parameter positions
val run = "The people' s Republic of China".run {
length >= 10
}
val with = with("The people' s Republic of China") {
length >= 10
}
}
5.also
also Functions and let Functions are similar , and let equally ,also It also passes the receiver as a value parameter to lambda, But it's a little different :also Return recipient object ,let return lambda result . such also Especially suitable for The same original object , Take advantage of side effects , because alos Receive this object when returning , You can Perform additional chained calls based on the original recipient object .
fun main() {
var fileContents:List<String>
//also and let Similar but will return the original object instead of lambda
val file = File("C://data.txt")
.also {
print(it.name)
}.also {
fileContents = it.readLines()
}
println(fileContents)
}
6.takeIf
It is a little different from other standard functions ,takeIf Functions need to be judged lambda Conditional expressions provided in , give true, from takeIf Function returns to receive the object , If it is false, Then return to null. As a result, it is necessary to judge whether a certain condition is satisfied , Then decide whether you can assign variables or perform a task .
fun main() {
//takeIf Put one in the last line boole Type of lambda by true Will return the original object by false Returns the null similar if else
val readText = File("")
.takeIf {
it.exists() && it.canRead()
}?.readText()
println(readText)
}
7.takeUnless
takelf Auxiliary function takeUnless, Only by judging the conditions you give, the result is false when ,takeUnIsee Will return the original recipient object .
fun main() {
//takeUnless And takeIf The effect is the same but opposite by false Will return the original object by true Returns the null
val readTextUnless = File("")
.takeUnless {
it.exists() && it.canRead()
}?.readText()
println(readTextUnless)
}
边栏推荐
- Wechat applet uploads pictures (preview deletion limits the size and number of pictures)
- Wechat applet custom tabbar (session customer service) vant
- Uni app disable native navigation bar
- Omron Ping replaces the large domestic product jy-v640 semiconductor wafer box reader
- Uniapp hides the scroll bar of scroll view
- Fichier local second Search Tool everything
- [MySQL] basic knowledge review
- 【var const let区别】
- App performance test: (II) CPU
- Wechat applet: use of global state variables
猜你喜欢
Echart柱状图:堆叠柱状图value格式化显示
Detailed explanation of Yanghui triangle
SSM框架整合--->简单后台管理
Echart折线图:当多条折线存在相同name,图例仍全部显示
USB debugging assistant (20191028)
Echart柱状图:echart实现堆叠柱状图
AI realizes "Resurrection" of relatives | old photo repair | old photo coloring, recommended by free app
JVM基础
Echart line chart: multiple line charts show only one line at a time
[solution] camunda deployment process should point to a running platform rest API
随机推荐
Uniapp dynamically shows / hides the navigation bar return button
Solutions to common problems in small program development
Logcat -b events and eventlogtags print the location correspondence of the events log in the code
IOError(Errors.E050.format(name=name))
AI实现亲人“复活”|老照片修复|老照片上色,免费APP推荐
[DP 01 backpack]
Applet Use of spaces
App performance test: (III) traffic monitoring
MFS詳解(七)——MFS客戶端與web監控安裝配置
Rk3399 hid gadget configuration
MFS详解(五)——MFS元数据日志服务器安装与配置
Download and installation of universal player potplayer, live stream m3u8 import
MFS详解(六)——MFS Chunk Server服务器安装与配置
超有范的 logo 在线设计制作工具
Echart line chart: different colors are displayed when the names of multiple line charts are the same
JS to realize bidirectional data binding
View绘制整体流程简析
SSM框架整合--->简单后台管理
Echart histogram: stack histogram value formatted display
Solution: vscode open file will always overwrite the last opened label