Corridor one inch lovesickness, fall into solitary leaning Back light and month spend Yin, trace is ten years ten years heart — — na LanRong if the corn poppy
In practice, strings are used all over the place, and if you don’t know how to do even the most basic things, isn’t it “JJ Smitta”? Therefore, in this article, we will explain the common operations on strings. For example, string interception, find, get length, replace and so on…
directory
String search
In the actual development of the string lookup function, only a few simple functions will be used, and I will only illustrate a few common ones.
1.1. Get the first element
Mainly contains the first () | firstOrNull () and first {} | firstOrNull {} four function
first()
|firstOrNull()
- Finds the first element of a string
- Difference: If the string is empty, the former is thrown
NoSuchElementException
Exception, which returnsnull
Ex. :
val str = "kotlin very good"
// NoSuchElementException is thrown if the string is empty
str.first() <=> str[0] <=> str.get(0)
// Returns null if the string is an empty string
str.firstOrNull()
Copy the code
first{}
|firstOrNull{}
- Finds the first element equal to a character
- Difference: If no element that meets the condition is found, the former throws
NoSuchElementException
Exception, which returnsnull
Ex. :
val str = "kotlin very good"
// NoSuchElementException is thrown if no element that meets the criteria is found
str.first{ it= ='o' }
// If no element is found, null is returned
str.firstOrNull{ it= ='o' }
Copy the code
1.2. Get the last element
First (), firstOrNull(), and first{} and firstOrNull{}
The last () and lastOrNull ()
- Finds the last element of a string
- Difference: If the string is empty, the former is thrown
NoSuchElementException
Exception, which returnsnull
Ex. :
val str = "kotlin very good"
// NoSuchElementException is thrown if the string is empty
// lastIndex is an extended attribute, and its implementation is length-1
str.last() <==> str.get(lastIndex) <==> str[lastIndex]
// Returns null if the string is an empty string
str.lastOrNull()
Copy the code
The last {} and lastOrNull {}
- Finds the last element equal to a character
- Difference: If no element that meets the condition is found, the former throws
NoSuchElementException
Exception, which returnsnull
Ex. :
val str = "kotlin very good"
// NoSuchElementException is thrown if no element that meets the criteria is found
// The string is reversed and then iterated to find the element that meets the condition. So I'm going to have to iterate less
str.last{ it= ='o' }
// If no element is found, null is returned
str.lastOrNull{ it= ='o' }
Copy the code
1.3. Find elements
1.3.2, find {} | findLast {} in fact find elements provides two higher-order functions find {}, findLast {}. Internally, however, firstOrNull() and lastOrNull() are called. There will be no elaboration here.
1.3.2 Find the subscript of the corresponding element
indexOf()
: Finds the first occurrence of an element or string in the original string.indexLastOf()
: Finds the last occurrence of an element or string in the original string.indexOfFirst{}
With:indexOf()
indexOfLast{}
With:indexLastOf()
Ex. :
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"))
Copy the code
The output is:
1
14
1
7
14
12
Copy the code
Second, string interception
If you have a programming background in Java or any other language. You should be familiar with string interception. You can go ahead and think of string interception as just a consolidation. Of course, you can skip this section because in Kotlin, the string interception function subString() calls the Java subString() function.
In Kotlin, in addition to calling subString() function, you can also call subSequence() function, interested friends can go to see the source code.
2.1, withsubString()
Function to intercept
Take a look at the source code for the subString() 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)
Copy the code
From the above source we can see that Kotlin is using the Java subString() function
Among them:
startIndex
Argument: Intercepting the beginning index of the stringendIndex
Argument: The end index of the truncated stringrang
Parameter, refers to oneIntRang
Type, representing a range
Example:
val str = "Kotlin is a very good programming language"
println("s = ${str.substring(10)}") // The end index is length-1 when only the start index is available
println(str.substring(0.15))
println(str.substring(IntRange(0.15)))
Copy the code
The output is:
a very good programming language
Kotlin is a ver
Kotlin is a very
Copy the code
Note:
- use
subString(startIndex,endIndex)
andsubString(rang)
When the difference. Can be seen from the above results combined with the source code. - Remember when subscripts are out of bounds. namely
StringIndexOutOfBoundsException
abnormal
2.2, withsubSequence()
Function to intercept
In Kotlin, in addition to intercepting a string using subString() as explained above, you can also intercept a string using the subSequence() function.
Let’s take a look at the source code implementation:
public fun subSequence(startIndex: Int, endIndex: Int): CharSequence
public fun CharSequence.subSequence(range: IntRange): CharSequence = subSequence(range.start, range.endInclusive + 1)
Copy the code
From the source, we can see that it is roughly the same as the subString() function, but it does not provide the case of passing only startIndex
Example:
val str = "Kotlin is a very good programming language"
println(str.subSequence(0.15))
println(str.subSequence(IntRange(0.15)))
Copy the code
The output is:
Kotlin is a ver
Kotlin is a very
Copy the code
String replacement
As with string interception above, you can skip this section if you have programming experience. For string substitution, Kotlin implements the Replace () HA function in Java as well as replaceFirst(), replaceAfter(), replaceBefore(), replaceIndent(), and so on. Examples of these functions are given below.
3.1. Replace () function
The replace() function provides four overloaded functions. They can perform different functions
3.1.1, the replace (oldChar, newChar ignoreCase = false)
Function: Replace a character in the original string with a new character. The new string is then returned
oldChar
: Indicates the character to be replacednewChar
: New characterignoreCase
: Whether to quoteJava
In thereplace()
Function. The default value isfalse
, which isJava
thereplace()
function
Ex. :
// Replace all characters' a 'with' a '
val str = "Kotlin is a very good programming language"
println(str.replace('a'.'A'))
Copy the code
The output is:
Kotlin is A very good progrAmming lAnguAge
Copy the code
3.1.2, replace (oldValue, newValue, ignoreCase = false)
Function: Replace a character in the original string with a new character. The new string is then returned
oldValue
: Indicates the string to be replacednewValue
: New stringignoreCase
: Whether to quoteJava
In thereplace()
Function. The default value isfalse
, which isJava
thereplace()
function
Ex. :
// Put the string`Kotlin`Replace it with a string`Java`
val str = "Kotlin is a very good programming language"
println(str.replace("Kotlin"."Java"))
Copy the code
The output is:
Java is a very good programming language
Copy the code
3.1.3, replace (regex, replacement)
Function: Matches the source string according to the defined regular rules, and replaces the string that meets the rules with a new string.
regex
: Regular expressionreplacement
: New string
Ex. :
// The rule of the regex is to check the number, if the number is replaced by the string 'kotlin'
val str = "1234a kotlin 5678 3 is 4"
println(str.replace(Regex("[0-9] +"),"kotlin"))
Copy the code
The output is:
kotlina kotlin kotlin kotlin is kotlin
Copy the code
3.1.4, replace(regex: regex, noinline transform: (MatchResult) -> CharSequence)
- Function: According to the defined regular rules to match the source string, the string that meets the rules through
transform{}
New string substitution for higher-order function mappings.regex
: Regular expressiontransform
: higher-order function
Ex. :
val str = "1234a kotlin 5678 3 is 4"
val newStr = str.replace(Regex("[0-9] +"), {"abcd "})
Copy the code
The output is:
abcd abcd abcd abcd a kotlin abcd abcd abcd abcd abcd is abcd
Copy the code
You can see the difference between the two functions above. The knowledge point about high order function, regular expression can see material understanding by oneself first. Xiao Sheng will fill in the relevant content in the following chapters…
The replace() function explained above. Several overloaded functions are also analyzed. The arguments in replace() are familiar. And the following functions do much the same thing. Therefore, I will only illustrate the functions of the following operations. The introduction of parameters will not be discussed in detail
3.2, replaceFirst ()
Function: Replaces the first character or string that meets the condition with a new character or string
Ex. :
val str = "Kotlin is a very good programming language"
println(str.replaceFirst('a'.'A'))
println(str.replaceFirst( "Kotlin"."Java"))
Copy the code
The output is:
Kotlin is A very good programming language
Java is a very good programming language
Copy the code
3.3, replaceBefore ()
Function: Intercepts the first character or the string after the conditional character, contains the conditional character or the string itself, and precedes it with a new string.
Ex. :
val str = "Kotlin is a very good programming language"
println(str.replaceBefore('a'."AA"))
println(str.replaceBefore("Kotlin"."Java"))
Copy the code
The output is:
AAa very good programming language
JavaKotlin is a very good programming language
Copy the code
3.4, replaceBeforeLast ()
Function: Intercepts the last character or the string after the conditional character, contains the conditional character or the string itself, and precedes it with a new string.
Ex. :
val str = "Kotlin is a very good programming language"
println(str.replaceBeforeLast('a'."AA"))
println(str.replaceBeforeLast("Kotlin"."Java"))
Copy the code
The output is:
AAage
JavaKotlin is a very good programming language
Copy the code
3.5, replaceAfter ()
Function: Intercepts the first character or the string before the conditional character, contains the conditional character or the string itself, and adds a new string after it.
Ex. :
val str = "Kotlin is a very good programming language"
println(str.replaceAfter('a'."AA"))
println(str.replaceAfter("Kotlin"."Java"))
Copy the code
The output is:
Kotlin is aAA
KotlinJava
Copy the code
3.6, replaceAfterLast ()
Function: Intercepts the last character or the string before the conditional character, contains the conditional character or the string itself, and adds a new string after it.
Ex. :
val str = "Kotlin is a very good programming language"
println(str.replaceAfterLast('a'."AA"))
println(str.replaceAfterLast("Kotlin"."Java"))
Copy the code
The output is:
Kotlin is a very good programming languaAA
KotlinJava
Copy the code
4. String segmentation
As in the previous section, Kotlin provides the splitToSequence() function to split strings in addition to implementing the Split () function in Java. After a successful partition, it returns a set of strings for subsequent operations.
4.1, the split ()
The split() function also provides four overloaded functions. Among them, regular expression is used for conditional segmentation of two. Use character split to occupy one. Use string splitting to occupy one.
4.1.1. Use regular expression segmentation
Regular expressions are used in Kotlin using the Regex class, while Java uses the Pattern class used by regular expressions. Here are some examples
Ex. :
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")
}
Copy the code
The output is:
kotlin java Lua JavaScript
kotlin java Lua JavaScript
Copy the code
4.1.2 Use character or string segmentation
In actual project development, this method is used more often. But it’s worth noting here that whether it’s a character split or a string split, it’s a mutable argument. That is, the number of parameters is variable.
Ex. :
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")
}
Copy the code
The output is:
Kotlin is a very good programming language
Kotlin is a very good programming language
Copy the code
Here is an example of a mutable argument 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")
}
Copy the code
The output is:
a b c d e f g h 2 3 4 5
Copy the code
4.2, splitToSequence ()
This function can also be split with strings or characters, just like the split() function above. I won’t go into details here…
Five, the other
In addition to the points mentioned above, there are many common processes, such as detecting whether a string is null or not, getting string length, string inversion, statistics, converting character arrays, getting characters with specified subscripts, and so on.
5.1. Get the string length
There are two ways to get the length of a string in Kotlin. In fact, it is also a kind of
- Use directly
length
Attribute fetch length- with
count()
Function get, actuallycount()
Function also returnslength
Length.
Example:
val str = "kotlin very good"
// 1. Use the length attribute
println("str.length => ${str.length}")
// 2. Use the count() function to get
println("str.count() => ${str.count()}")
Copy the code
The output is:
str.length => 16
str.count() => 16
Copy the code
Here we take a look at the source code for the count() function
/ * *
* Returns the length of this char sequence.
* return the length attribute...
* /
@kotlin.internal.InlineOnly
public inline fun CharSequence.count(a): Int {
return length
}
Copy the code
5.2 Statistics of repeated characters
The count() function returns the length property to get the length of the string. In fact, the source code also provides a higher-order function called count{}, used to count the number of repeated characters in a string.
/ *
Count {} function source
This function accepts a Lambda expression of type Boolean. I then loop through the string and increment the variable 'count' if my condition is true.
Return the number of repeats' count 'when the loop is complete
* /
public inline fun CharSequence.count(predicate: (Char) -> Boolean) :Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
Copy the code
Example:
val str = "kotlin very good"
val count = str.count { it= ='o' }
println("count : $count")
Copy the code
The output is:
count : 3
Copy the code
5.3. Validate Strings
In real development, especially Android development, it is often the case to verify that the content of the input field is an empty string. In Kotlin, as in Java, several functions are provided to handle this situation.
The following functions handle empty or null strings:
isEmpty()
: Its source is judged by itslength
Is equal to0
If, is equal to the0
It returnstrue
, otherwise returnfalse
. Cannot be used directly for nullable stringsisNotEmpty()
: Its source is judged by itslength
If more than0
, if more than0
It returnstrue
, otherwise returnfalse
. Cannot be used directly for nullable stringsisNullOrEmpty()
: the source is to determine whether the string isnull
Or itslength
Whether is equal to the0
.isBlank()
: Its source is judged by itslength
Whether is equal to the0
, or whether the number of Spaces it contains is equal to the currentlength
. Cannot be used directly for nullable stringsisNotBlank()
: Its source code is rightisBlank()
I’m going to invert the function. Cannot be used directly for nullable stringsisNotOrBlank()
: its source determines whether the string isnull
. Or callisBlank()
function
Example:
val str : String? = "kotlin"
/ *
As you can see, when STR isNullOrEmpty, isNullOrEmpty() and isNotOrBlank() can be called without doing any processing
, and the other functions don't
* /
str? .isEmpty()//false
str? .isNotEmpty()// true
str.isNullOrEmpty() //false
str? .isBlank()//false
str? .isNotBlank()//true
str.isNullOrBlank() //false
Copy the code
5.4 string concatenation
String links can only be linked using + in Java, except for StringBuilder and StringBuffer. In Kotlin, you can use the plus() function in addition to +. It accepts any type. The plus() function is an operator overload function. This was explained in the previous chapter. If you are not familiar with Cloud overloading in Kotlin, you can check out my other article: Kotlin — Primer (5) : Operator overloading one
Example explanation:
val oldStr = "kotlin"
println(oldStr.plus(" very good"))
println(oldStr + " very good")
Copy the code
The output is:
kotlin very good
kotlin very good
Copy the code
5.5. String inversion
Like arrays, strings can invert elements. Use the reversed() function directly.
Ex. :
val str = "kotlin"
println("String inversion:${str.reversed()}")
Copy the code
Output result:
String inversion: niltok
Copy the code
Determine the start and end of the string
5.6.1, startsWith ()
Function: Checks whether the string starts with a character or a string.
char
: Start characterprefix
: start stringignoreCase
: Whether to callJava
This function in. The default isfalse
startIndex
: Starting position
Ex. :
val str = "kotlin"
println(str.startsWith('k')) // Whether the character 'k' starts
println(str.startsWith("Kot")) // Whether to start with the string 'kot'
println(str.startsWith("lin".3)) // Whether to start with the string 'Lin' when the start position is 3
Copy the code
The output is:
true
true
true
Copy the code
5.6.2, endsWith ()
Function: Checks whether the string ends with a character or a string.
char
: End charactersuffix
: Ending stringignoreCase
: Whether to callJava
This function in. The default isfalse
Ex. :
val str = "kotlin"
println(str.endsWith("lin")) // Whether to end with the string 'Lin'
println(str.endsWith('n')) // Whether to end with character 'n'
Copy the code
The output is:
true
true
Copy the code
conclusion
In practice, strings are handled in many ways. In particular, string verification processing, replacement, segmentation, interception. That’s why I’ve put these things together. These are very basic, but also very common. If you have programming experience, you should consolidate the basic knowledge of strings. The string manipulation in Kotlin is finished here, but there are many other functions, although not used much in development, but we should at least have an understanding of them. Interested friends can go to see the implementation of its source code.
This article has been collected on GitHub: Jetictors/KotlinLearn, welcome star articles continue to update, can be wechat search “J guy talk” first time read, everyone’s three-in-one is the best power for the old J, you are sure not to wave? If you have any mistakes or suggestions on this blog, please leave comments