Table of contents
6.1. Character search is implemented by default
6.2. Implementation using kotlin extension
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
NoSuchElementException
an 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
NoSuchElementException
an 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
NoSuchElementException
an 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
NoSuchElementException
an 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 Java
or 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 Java
in subString()
.
In Kotlin
addition 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 Kotlin
is usedJava
subString()
in:
startIndex
Parameters: the start subscript of the intercepted stringendIndex
Parameter: the end subscript of the intercepted stringrang
Parameter, refers to aIntRang
type, 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)
andsubString(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
StringIndexOutOfBoundsException
abnormal
2.2. subSequence()
Intercept with function
In addition to using the interception string Kotlin
explained 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 startIndex
transfer
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 Kotlin
the implementation , it also provides other functions such as , , , , and so on. The meaning of these functions will be explained with examples below.Java
replace()
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 replacednewChar
: new characterignoreCase
: Whether to reference the functionJava
inreplace()
. The default valuefalse
is the ready-to-Java
usereplace()
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 replacednewValue
: new stringignoreCase
: Whether to reference the functionJava
inreplace()
. The default valuefalse
is the ready-to-Java
usereplace()
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 expressionreplacement
: 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 expressiontransform
: 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 Kotlin
the implementation , functions are provided to split strings. After the split is successful, a string collection will be returned for our subsequent operations.Java
split()
splitToSequence()
4.1、 split()
split()
The function also provides 4
an 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
Kotlin
To use a regular expression in , you are using a class Regex
, and Java
to use a regular expression in , you are using Pattern
a 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, null
getting 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
Kotlin
are two ways to get the length of a string in . Actually it's just one
- Get the length directly with
length
the attribute- Get it with
count()
a function. In fact,count()
the method of the function also returnslength
the 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 length
the 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 Android
development, it is often encountered when verifying whether the content of the input box is an empty string. In Kotlin
, as in , Java
several 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 itlength
is equal0
, if it is equal0
, it will returntrue
, otherwise it will returnfalse
. Cannot be used directly with nullable stringsisNotEmpty()
length
: Its source code is to judge whether it is greater than0
, if it is greater than ,0
returntrue
, otherwise returnfalse
. Cannot be used directly with nullable stringsisNullOrEmpty()
: Its source code is to judge whether the string is or whethernull
it is equal to .length
0
isBlank()
length
: Its source code is to judge whether it is equal to0
, or to judge whether the number of spaces it contains is equal to the current onelength
. Cannot be used directly with nullable stringsisNotBlank()
: Its source code is toisBlank()
reverse the function. Cannot be used directly with nullable stringsisNotOrBlank()
: Its source code judges whether the string isnull
. or callisBlank()
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 Java
can only be used +
to link in, except of StringBuilder、StringBuffer
course. In Kotlin
addition 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 characterprefix
: starting stringignoreCase
: whether to callJava
this 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 charactersuffix
: ending stringignoreCase
: whether to callJava
this 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.