Kotlin summary summary

Table of contents

1. String search

2. String interception

3. String replacement

Fourth, string segmentation

5. Others

Six, Kotlin extension

6.1. Character search is implemented by default

 6.2. Implementation using kotlin extension

6.3. Call 

7. Summary


1. String search

In the actual development of the string search function, only a few simple functions are used. Here I only explain a few commonly used ones.

1.1. Get the first element

Mainly contains first()| firstOrNull()and first{}| firstOrNull{}four functions

first() | firstOrNull()

  • Function: Find the first element of a string
  • Difference: If the string is an empty string, the former will throw NoSuchElementExceptionan exception, and the latter will returnnull

example:

val str = "kotlin very good"// 如果字符串为空串时,会抛出NoSuchElementException异常
str.first()   <=>   str[0]   <=>   str.get(0)// 如果字符串为空串时,会返回nullstr.firstOrNull()

first{}|firstOrNull{}

  • Function: Find the first element equal to a certain character
  • Difference: No element meeting the condition is found, the former will throw NoSuchElementExceptionan exception, and the latter will returnnull

example:

val str = "kotlin very good"// 如果未查找到满足条件的元素,会抛出NoSuchElementException异常
str.first{ it == 'o' } // 如果未查找到满足条件的元素,会返回nullstr.firstOrNull
{ it == 'o' } 

1.2. Get the last element

It mainly includes four functions of first(), firstOrNull()and first{}andfirstOrNull{}

last()andlastOrNull()

  • Function: Find the last element of a string
  • Difference: If the string is an empty string, the former will throw NoSuchElementExceptionan exception, and the latter will returnnull

example:

val str = "kotlin very good"// 如果字符串为空串时,会抛出NoSuchElementException异常
// 其中 lastIndex 是一个拓展属性,其实现是
length - 1str.last()   <==>   str.get(lastIndex)   <==>  str[lastIndex]// 如果字符串为空串时,会返回nullstr.lastOrNull()

last{}andlastOrNull{}

  • Function: Find the last element equal to a certain character
  • Difference: No element meeting the condition is found, the former will throw NoSuchElementExceptionan exception, and the latter will returnnull

example:

val str = "kotlin very good"// 如果未查找到满足条件的元素,会抛出NoSuchElementException异常
// 其实从源码中我们发现其是对原字符串反转之后再进行遍历查找满足条件的元素。这样遍历的次数就减少了
str.last{ it == 'o' } // 如果未查找到满足条件的元素,会返回nullstr.lastOrNull{ it == 'o' } 

1.3. Find elements

1.3.2, find{} | findLast{}
actually provides two high-order functions for finding elements find{}, findLast{}. However, its internals are all calls firstOrNull()and lastOrNull()functions for processing. There is not much to say here.

1.3.2. Find the subscript of the corresponding element

  • indexOf(): Find the first subscript of an element or string in the original string.
  • indexLastOf(): Find the subscript of the last occurrence of an element or string in the original string.
  • indexOfFirst{}: sameindexOf()
  • indexOfLast{}: sameindexLastOf()

example:

val str = "kotlin very good"
println(str.indexOfFirst { it == 'o' })
println(str.indexOfLast { it == 'o' })
println(str.indexOf('o',0))
println(str.indexOf("very",0))
println(str.lastIndexOf('o'))
println(str.lastIndexOf("good"))

The output is:

114171412

2. String interception

If you have Javaor programming foundation in other languages. I believe you should be familiar with string interception. You can continue to look down, just as a consolidation of string interception. Of course, you can also skip this section directly, because in Kotlin, the function of string interception subString()is to call the function Javain subString().

In Kotlinaddition to calling subString()functions, you can also call subSequence()functions. Friends who are interested can go to see the source code.

2.1. subString()Intercept with function

Let's take a look at subString()the source code of the function

@kotlin.internal.InlineOnly
public inline fun String.substring(startIndex: Int): String = (this as java.lang.String).substring(startIndex)
@kotlin.internal.InlineOnly
public inline fun String.substring(startIndex: Int, endIndex: Int): String = (this as java.lang.String).substring(startIndex, endIndex)
public fun String.substring(range: IntRange): String = substring(range.start, range.endInclusive + 1)

From the above source code, we can see that the function in Kotlinis usedJavasubString()

in:

  • startIndexParameters: the start subscript of the intercepted string
  • endIndexParameter: the end subscript of the intercepted string
  • rangParameter, refers to a IntRangtype, representing a range

Example:

val str = "Kotlin is a very good programming language"
println("s = ${str.substring(10)}")  // 当只有开始下标时,结束下标为length - 1
println(str.substring(0,15))println(str.substring(IntRange(0,15)))

The output is:

a very good programming languageKotlin is a verKotlin is a very

Notice:

  • The difference between using subString(startIndex,endIndex)and subString(rang)when. It can be seen from the above results combined with the source code.
  • Keep in mind the subscript out-of-bounds case. that is StringIndexOutOfBoundsExceptionabnormal

2.2. subSequence()Intercept with function

In addition to using the interception string Kotlinexplained above , you can also use function interception.subString()subSequence()

Let's take a look at its source implementation:

public fun subSequence(startIndex: Int, endIndex: Int): CharSequence
public fun CharSequence.subSequence(range: IntRange): CharSequence = subSequence(range.start, range.endInclusive + 1)

From the source code, we can see that it is roughly the subString()same as a function, but it does not provide only startIndextransfer

Example:

val str = "Kotlin is a very good programming language"
println(str.subSequence(0,15))
println(str.subSequence(IntRange(0,15)))

The output is:

Kotlin is a verKotlin is a very

3. String replacement

As with string truncation above, you can skip this section if you have programming experience. However, for the string replacement function, in addition to the ha function in Kotlinthe implementation , it also provides other functions such as , , , , and so on. The meaning of these functions will be explained with examples below.Javareplace()replaceFirst()replaceAfter()replaceBefore()replaceIndent()

3.1, replace() function

replace()The function provides 4 overloaded functions. They can perform different functions

3.1.1、 replace(oldChar,newChar,ignoreCase = false)

Function: Replace all the characters in the original string with new characters. then return the new string

  • oldChar: The character to be replaced
  • newChar: new character
  • ignoreCase: Whether to reference the function Javain replace(). The default value falseis the ready-to- Javause replace()function

example:

// 把字符`a`全部替换为`A`
val str = "Kotlin is a very good programming language"
println(str.replace('a','A'))

The output is:

Kotlin is A very good progrAmming lAnguAge

3.1.2、 replace(oldValue,newValue,ignoreCase = false)

Function: Replace all the characters in the original string with new characters. then return the new string

  • oldValue: the string to be replaced
  • newValue: new string
  • ignoreCase: Whether to reference the function Javain replace(). The default value falseis the ready-to- Javause replace()function

example:

// 把字符串`Kotlin`替换成字符串`Java`val str = "Kotlin is a very good programming language"
println(str.replace("Kotlin","Java"))

The output is:

Java is a very good programming language

3.1.3、 replace(regex,replacement)

Function: Match the source string according to the defined regular rules, and replace the strings that meet the rules with new strings.

  • regex: regular expression
  • replacement: new string

example:

// 正则的规则为检测数字,如果为数字则替换成字符串`
kotlin`val str = "1234a kotlin 5678 3 is 4"
println(str.replace(Regex("[0-9]+"),"kotlin"))

The output is:

kotlina kotlin kotlin kotlin is kotlin

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

  • Function: Match the source string according to the defined regular rules, and transform{}replace the strings satisfying the rules with new strings mapped by higher-order functions.
  • regex: regular expression
  • transform: higher order function

example:

val str = "1234a kotlin 5678 3 is 4"
val newStr = str.replace(Regex("[0-9]+"),{"abcd "})

The output is:

abcd abcd abcd abcd a kotlin abcd abcd abcd abcd  abcd  is abcd

You can see the difference between the two functions from the above two functions. You can read the information on your own to understand the knowledge points 高阶函数about . 正则表达式Xiaosheng will add relevant content in subsequent chapters...

After the explanation of the above replace()function. And several overloaded functions are analyzed. I believe that everyone replace()has a general understanding of the parameters in the function. And the following functions are roughly the same operation. Therefore, in the following several function operations, I will only illustrate their functions with examples. The introduction of the parameters will not be studied in detail.

3.2、replaceFirst()

Function: replace the first character or string that meets the condition with a new character or string

example:

val str = "Kotlin is a very good programming language"
println(str.replaceFirst('a','A'))
println(str.replaceFirst( "Kotlin","Java"))

The output is:

Kotlin is A very good programming languageJava is a very good programming language

3.3、replaceBefore()

Function: Intercept the first character that meets the condition or the string after the string, including the character that meets the condition or the string itself, and add a new string in front of it.

example:

val str = "Kotlin is a very good programming language"
println(str.replaceBefore('a',"AA"))
println(str.replaceBefore("Kotlin","Java"))

The output is:

AAa very good programming languageJavaKotlin is a very good programming language

3.4、replaceBeforeLast()

Function: Intercept the last character that meets the condition or the string after the string, including the character that meets the condition or the string itself, and add a new string in front of it.

example:

val str = "Kotlin is a very good programming language"
println(str.replaceBeforeLast('a',"AA"))
println(str.replaceBeforeLast("Kotlin","Java"))

The output is:

AAageJavaKotlin is a very good programming language

3.5、replaceAfter()

Function: Intercept the first character that meets the condition or the string in front of the string, including the character that meets the condition or the string itself, and add a new string after it.

example:

val str = "Kotlin is a very good programming language"
println(str.replaceAfter('a',"AA"))
println(str.replaceAfter("Kotlin","Java"))

The output is:

Kotlin is aAAKotlinJava

3.6、replaceAfterLast()

Function: Intercept the last character that satisfies the condition or the string before the string, including the character or string itself that meets the condition, and add a new string after it.

example:

val str = "Kotlin is a very good programming language"
println(str.replaceAfterLast('a',"AA"))
println(str.replaceAfterLast("Kotlin","Java"))

The output is:

Kotlin is a very good programming languaAAKotlinJava

Fourth, string segmentation

As in the previous section, in addition to the functions in Kotlinthe implementation , functions are provided to split strings. After the split is successful, a string collection will be returned for our subsequent operations.Javasplit()splitToSequence()

4.1、 split()

split()The function also provides 4an overloaded function. Among them, using a regular expression as a conditional split occupies two. Split with characters to occupy one. Splitting with a string occupies one.

4.1.1. Using regular expressions to split

KotlinTo use a regular expression in , you are using a class Regex, and Javato use a regular expression in , you are using Patterna class. Here are examples

example:

var str2 = "1 kotlin 2 java 3 Lua 4 JavaScript"
val list3 = str2.split(Regex("[0-9]+"))
for (str in list3){   
print("$str \t")
}
println()
val list4 = str2.split(Pattern.compile("[0-9]+"))
for (str in list4){    
print("$str \t")
}

The output is:

kotlin  java  Lua  JavaScript     kotlin  java  Lua  JavaScript     

4.1.2, use characters or strings to split

In actual project development, this method is used more often. However, it is worth noting here that whether it is split by characters or by strings, it is a variable parameter. That is, the number of its parameters is indefinite.

example:

val str1 = "Kotlin is a very good programming language"
val list1 = str1.split(' ')
for (str in list1)
{   
print("$str \t")
}
println()
val list2 = str1.split(" ")
for (str in list2)
{   
print("$str \t")
}

The output is:

Kotlin   is   a   very     good    programming     languageKotlin   is   a   very     good    programming     language

Here is an example of a variable parameter case:

val str3 = "a b c d e f g h 2+3+4+5"val list5 = str3.split(' ','+')for (str in list5){    print("$str \t")}

The output is:

a     b   c   d   e   f   g   h   2   3   4   5 

4.2、 splitToSequence()

This function can also be divided by string or character, and its usage is the same as the above split()function. Not much to say here...

5. Others

In addition to the points explained above, there are many commonly used processing, such as detecting whether the string is an empty string, whether it is, nullgetting the length of the string, reversing the string, counting, converting the character array, getting the character of the specified subscript, and so on.

5.1. Get the string length

There Kotlinare two ways to get the length of a string in . Actually it's just one

  1. Get the length directly with lengththe attribute
  2. Get it with count()a function. In fact, count()the method of the function also returns lengththe length.

Example:

val str = "kotlin very good"// 1. 直接用length属性获取println("str.length => ${str.length}")// 2. 用count()函数获取println("str.count() => ${str.count()}")

The output is:

str.length => 16str.count() => 16

Here we take a look at count()the source code of the function

/** * Returns the length of this char sequence. * 其实也就是返回了length属性... */
@kotlin.internal.InlineOnly
public inline fun CharSequence.count(): Int 
{    
return length
}

5.2. Statistics of repeated characters

The function mentioned above count()is to return lengththe length of the attribute to obtain the string. In fact, the source code also provides a count{}higher-order function called , which is used to count the number of repeated characters in a string.

/*  count{}函数源码    该函数接受一个`Boolean`类型的`Lambda`表达式。然后循环这个字符串,如果我的条件成立,则变量`count`自增。  循环完成之后返回重复的个数`count` */
public inline fun CharSequence.count(predicate: (Char) -> Boolean): Int 
{ 
var count = 0  
for (element in this)
if (predicate(element)) count++    
return count
}

Example:

val str = "kotlin very good"
val count = str.count
{ it == 'o' }
println("count : $count")

The output is:

count : 3

5.3, Verification string

In actual development, especially in Androiddevelopment, it is often encountered when verifying whether the content of the input box is an empty string. In Kotlin, as in , Javaseveral functions are provided to handle this situation.

The following functions all handle strings that are empty or empty:

  • isEmpty(): Its source code is to judge whether it lengthis equal 0, if it is equal 0, it will return true, otherwise it will return false. Cannot be used directly with nullable strings
  • isNotEmpty()length: Its source code is to judge whether it is greater than 0, if it is greater than , 0return true, otherwise return false. Cannot be used directly with nullable strings
  • isNullOrEmpty(): Its source code is to judge whether the string is or whether nullit is equal to .length0
  • isBlank()length: Its source code is to judge whether it is equal to 0, or to judge whether the number of spaces it contains is equal to the current one length. Cannot be used directly with nullable strings
  • isNotBlank(): Its source code is to isBlank()reverse the function. Cannot be used directly with nullable strings
  • isNotOrBlank(): Its source code judges whether the string is null. or call isBlank()the function

Example:

val str : String? = "kotlin"
/*   可以看出当str为可空变量的时候,isNullOrEmpty()和isNotOrBlank()可以不做直接调用而不做任何处理  ,而其他的函行 */
str?.isEmpty()          
falsestr?.isNotEmpty()        
truestr.isNullOrEmpty()       
falsestr?.isBlank()           
falsestr?.isNotBlank()      
truestr.isNullOrBlank()       //false

5.4, ​​string concatenation

String links Javacan only be used +to link in, except of StringBuilder、StringBuffercourse. In Kotlinaddition to using functions +, you can also use plus()functions. It accepts any type. plus()function is an operator overloaded function.
Example explanation:

val oldStr = "kotlin"
println(oldStr.plus(" very good"))
println(oldStr + " very good")

The output is:

kotlin very goodkotlin very good

5.5, string reversal

Like arrays, strings can have their elements reversed. Just use reversed()the function directly.

example:

val str = "kotlin"println("字符串反转:${str.reversed()}")

Output result:

字符串反转:niltok

5.6. Determine the start and end of a string

5.6.1、 startsWith()

Function: To judge whether its string starts with a certain character or string.

  • char: start character
  • prefix: starting string
  • ignoreCase: whether to call Javathis function in. The default isfalse
  • startIndex: start position

example:

val str = "kotlin"    
println(str.startsWith('k'))         // 是否有字符`k`起始   
println(str.startsWith("Kot"))       // 是否由字符串`kot`起始  
println(str.startsWith("lin",3))     // 当起始位置为3时,是否由字符串`lin`起始

The output is:

truetruetrue

5.6.2、endsWith()

Function: To judge whether the string ends with a certain character or string.

  • char: ending character
  • suffix: ending string
  • ignoreCase: whether to call Javathis function in. The default isfalse

example:

val str = "kotlin"println(str.endsWith("lin"))  // 是否由字符串`lin`结尾
println(str.endsWith('n'))    // 是否由字符`n`结尾复制代码

The output is:

truetrue

Six, Kotlin extension

6.1. Character search is implemented by default

object StringUtil { 
 fun lettersCount(str: String): Int { 
 var count = 0 
 for (char in str) { 
 if (char.isLetter()) { 
 count++ 
 } 
 } 
 return count 
 } 
}

 6.2. Implementation using kotlin extension

fun String.lettersCount(): Int { 
 var count = 0 
 for (char in this) { 
 if (char.isLetter()) { 
 count++ 
 } 
 } 
 return count 
} 

6.3. Call 

val count = "ABC123xyz!@#".lettersCount() 

 

7. Summary

In actual development, there are many situations in which strings are processed and used. Especially the verification processing, replacement, segmentation, and interception of strings. This is why I sorted out these knowledge points. These knowledge points are very basic, but they are also very commonly used. If you have programming experience, you should consolidate the basic knowledge of strings.

Guess you like

Origin blog.csdn.net/qq_41264674/article/details/130107826