当前位置:网站首页>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)
}
边栏推荐
- 微信小程序:点击事件获取当前设备信息(基础)
- 【新手上路常见问答】关于技术管理
- 线程相关点
- 微信小程序:基础复习
- USB status error and its cause (error code)
- [DP 01 backpack]
- Uniapp secondary encapsulates uview components, and the parent component controls display and hiding
- Wechat applet (function transfer parameters, transfer multiple parameters, page Jump)
- Local file search tool everything
- [one · data 𞓜 simple implementation of the leading two-way circular linked list]
猜你喜欢
Echart line chart: multiple line charts show only one line at a time
MFS details (vii) - - MFS client and Web Monitoring installation configuration
【ONE·Data || 带头双向循环链表简单实现】
Free screen recording software captura download and installation
楊輝三角形詳解
Omron Ping replaces the large domestic product jy-v640 semiconductor wafer box reader
Binary search
Echart line chart: different colors are displayed when the names of multiple line charts are the same
js将文本转成语言播放
AI实现亲人“复活”|老照片修复|老照片上色,免费APP推荐
随机推荐
Dart class inherits and implements mixed operators
App performance test: (IV) power
免费录屏软件Captura下载安装
SSM integration
Echart histogram: stack histogram value formatted display
Rk3399 hid gadget configuration
MFS详解(七)——MFS客户端与web监控安装配置
本地文件秒搜工具 Everything
JVM Foundation
[written examination questions of meituan]
微信小程序:点击事件获取当前设备信息(基础)
Wechat applet development (requesting background data and encapsulating request function)
JVM基础
Uni app upload file
Wechat applet: use of global state variables
Wechat applet (pull-down refresh data) novice to
Uniapp dynamically shows / hides the navigation bar return button
Download and installation of universal player potplayer, live stream m3u8 import
Applet disable native top
Fragment lifecycle