String creation
The String class represents an array of type char. Strings are immutable, which means that the length and elements cannot be changed after creation. Because string objects are immutable, they can be shared.
fun main(a) {
val ch = charArrayOf('S'.'h'.'u'.'a'.'i'.'C'.'i')
val str = String(ch)
println(str)//ShuaiCi
}
Copy the code
Unlike Java, Kotlin does not need to use the new keyword to instantiate objects of the String class. A String can simply be declared in double quotes (“”), called an escaped String, or triple quotes (“”” “””), called an original String.
fun main(a) {
val kotlin = "Kotlin"
val android = """Android"""
println("$kotlin-$android")//Kotlin-Android
}
Copy the code
1.1 String Attributes
attribute | describe |
---|---|
length: Int |
Returns the length of a sequence of strings. |
indices: IntRange |
Returns the currentchar The range of valid character indexes in a sequence. |
lastIndex: Int |
returnchar The index of the last character in the sequence. |
1.2 String Functions
function | describe |
---|---|
compareTo(other: String): Int |
Compares the current object to the specified object to get the order. ifcurrent Is equal to another object specified0 . |
get(index: Int): Char |
Returns the character at the given index in the current character sequence. |
plus(other: Any?) : String |
Returns a connection string containing a string representation for a given other string. |
subSequence(startIndex: Int,endIndex: Int): CharSequence |
Returns from the current character sequencestartIndex Start toendIndex New character sequence |
CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false):Boolean |
Returns if the character sequence contains the specified character sequencetrue . |
CharSequence.count(): Int |
returnchar The length of the sequence. |
String.drop(n: Int): String |
Delete the formern Returns a string after the number of characters. |
String.dropLast(n: Int): String |
Delete the last onen Returns a string after the character. |
String.dropWhile(predicate: (Char) -> Boolean): String |
Returns a sequence of characters that contains all characters except the first character that satisfies the given predicate. |
CharSequence.elementAt(index: Int): Char |
Returns the character at the given index, or throws if the index does not exist in the character sequenceIndexOutOfBoundsException . |
CharSequence.indexOf(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int |
Returns the index of the first occurrence of a given character, starting with the given index value. |
CharSequence.indexOfFirst(predicate: (Char) -> Boolean): Int |
Returns the index of the first character that matches the given predicate, or if the character sequence does not contain any such character- 1 . |
CharSequence.getOrElse(index: Int, defaultValue: (Int) ->Char): Char |
If the index is outside the range of the current character sequence, it returns the character or call at the specified indexdefaultValue The result of the function. |
CharSequence.getOrNull(index: Int): Char? |
It returns the character at the given index, or if the index is outside the range of the character sequencenull . |
Second, string interception
2.1 the substring () function
The substring function supports arguments of type IntRange (representing a range of integers). The range created by until does not include a limit value.
/** * returns the substring specified by the given range index. * /
public fun String.substring(range: IntRange):
// Note here: range.endinclusive + 1
String = substring(range.start, range.endInclusive + 1)
/** * returns a substring of characters in the range of this character sequence starting with [startIndex] and ending before [endIndex]. * *@paramStartIndex startIndex (inclusive). *@paramEndIndex Ends an index (exclusive). If not specified, the length of the character sequence is used. * /
@kotlin.internal.InlineOnly
public inline fun CharSequence.substring(startIndex: Int, endIndex: Int = length): String = subSequence(startIndex, endIndex).toString()
/** * returns the character substring at the specified range index of this character sequence. * /
public fun CharSequence.substring(range: IntRange): String = subSequence(range.start, range.endInclusive + 1).toString()
Copy the code
If you look at this, you can see that they still end up calling the String.subsequence () function. So let’s look at substring first.
// String interception
var intercept = "Write better Android apps faster with Kotlin."
println(intercept.length)/ / 45
println(intercept.substring(10))//er Android apps faster with Kotlin.
println(intercept.substring(10.18))//er Andro
println(intercept.substring(10 until 18))//er Andro
println(intercept.substring(IntRange(10.18)))//er Androi
Copy the code
Difference between using subString(startIndex,endIndex) and subString(rang). Combined with the source code and examples can be seen.
The subscript crossing the line
As shown in the above code, the string length of Intercept is 45. Let’s look at the following code:
println(intercept.substring(30.46))
println(intercept.substring(IntRange(30.46)))
Copy the code
Remember when subscripts are out of bounds. The abnormal StringIndexOutOfBoundsException
2.2 subSequence () function
Returns a new character sequence from startIndex to endIndex from the current character sequence
var intercept = "Write better Android apps faster with Kotlin."
println(intercept.length)/ / 45
println(intercept.subSequence(10.18))//er Andro
Copy the code
3. String segmentation
The split function returns List data, and Lst supports the split syntax feature, which allows you to assign multiple variables in a single expression. Split is often used to simplify variable assignments.
3.1 Use character or string Segmentation
In actual project development, both Java and Kotlin use this approach 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.
// String split
var cf = "Android|Java|Kotlin"
var data = cf.split("|")
Copy the code
This is similar to Java, except it returns a List of data.
Deconstruction of grammar
// Deconstruct syntax features
var (zero,one,two)= cf.split("|")
println("$zero-$one-$two")
Copy the code
3.2 Using regular expression segmentation
Regular expressions are used in Kotlin using the Regex class, while Java uses the Pattern class used by regular expressions.
var dataRegex = cf.split(Regex("[ao]"))
//[Andr, id|J, v, |K, tlin]
println(dataRegex.toString())
dataRegex = cf.split(Pattern.compile("[ao]"))
//[Andr, id|J, v, |K, tlin]
println(dataRegex.toString())
Copy the code
String replacement
In addition to implementing the Replace () function in Java, Kotlin provides additional functions such as replaceFirst(), replaceAfter(), replaceBefore(), and replaceIndent().
4.1 the replace () function
The replace() function provides four overloaded functions. They can perform different functions
4.1.1 Replace (oldValue: String, newValue: String, ignoreCase: Boolean = false)
Replace all characters in the original string with new characters. The new string is then returned
- OldChar: the character to be replaced
- NewChar: indicates the new character
- IgnoreCase: Whether to reference the Replace () function in Java. The default value is false, using the Java replace() function
var th = "Write better Android apps faster with Kotlin."
// replace all characters t with!
println(th)
println(th.replace("t"."!"))
Copy the code
4.1.2 Replace (regex: regex, noinline transform: (MatchResult) -> CharSequence)
The source string is matched according to the defined regular rules, and the string that meets the rules is replaced by the new string mapped by the transform{} higher-order function.
- Regex: A regular expression used to determine which characters to replace
- Transform: High-order function (anonymous function that determines how to replace characters found in a regular expression search)
var reg= th.replace(Regex("[rte]")) {when(it.value){
"r" ->"Seven"
"t" ->"!"
"e" ->"5"
else -> it.value
}
}
println(reg)
Copy the code
The other two functions won’t take up space; they are used the same way.
4.2 replaceFirst () function
Replaces the first character or string satisfying the condition with a new character or string.
// Replace the first character A with V
println(th.replaceFirst("e"."V"))
// replace the first string er with Victory
println(th.replaceFirst("er"."Victory"))
Copy the code
4.3 replaceAfter () function
Intercepts the first character or string preceding the conditional character, including the conditional character or the string itself, and appending a new string after it.
// Intercepts the character p followed by Kotlin
println(th.replaceAfter("p"."Kotlin"))
// Take the string Android and append it to the string
println(th.replaceAfter("Android"."Handsome"))
Copy the code
4.4 replaceBefore () function
Intercepts the first character or the string after the conditional character, including the conditional character or the string itself, and prefixes it with a new string.
// Intercepts the character p and prefixes it with Kotlin
println(th.replaceBefore("p"."Kotlin"))
// Intercepts the string Android and prefixes it with a header
println(th.replaceBefore("Android"."Handsome"))
Copy the code
4.5 replaceIndent () function
Detects the common minimum indentation and replaces it with the specified newIndent.
var indent = " aaa aaaA"
println(indent)
// Detects the usual minimum indentation and replaces it with the specified newIndent.
println(indent.replaceIndent())
// Detect the universal minimum indentation of all input lines and remove it from each line, or if the first and last lines are blank (note the difference between blank and empty)
println(indent.trimIndent())
Copy the code
5. String comparison
In Kotlin, we use == to check whether characters in two strings match, and we use === to check whether two variables point to the same object on the memory heap. In Java, we use equals for reference comparisons and content comparisons.
= =
和 = = =
// String comparison
val str1 = "Kotlin"
val str2 = "Kotlin"
val str3 = "kotlin".replace("k"."K")
println("$str1-$str2-$str3")
// Compare the content, true
println(str1 == str2)//true
println(str1 == str3)//true
Java and Kotlin have a string constant pool
println(str1 === str2)//true
println(str1 === str3)//false
Copy the code
Constant pooling: Created for the convenience of creating certain objects quickly. When an object is needed, you can take one out of the pool (or create one if there is none in the pool), saving a lot of time when you need to create equal variables repeatedly. A constant pool is simply a memory space that exists in a method area.
The String class is also the most commonly used class in Java, and also implements constant pool technology for the convenience of creating Strings.
equals
val str1 = "Kotlin"
val str2 = "Kotlin"
val str4 = "kotlin"
println(str1.equals(str2))//true
println(str1.equals(str4))//false
// The second argument is true to ignore case comparisons.
// Add false to the second argument to indicate that case comparisons are not ignored.
println(str1.equals(str4,true))//true
Copy the code
String search
6.1 Getting the first element
6.1.1 First () and first{} functions
var seek = "Write better Android apps faster with Kotlin."
println(seek.first())
// Find the first element equal to a character
var data = seek.first {
it == 'A'
}
println(data)
Copy the code
FirstOrNull () and firstOrNull{} :
-
If the string is empty, first() throws an exception and firstOrNull() returns NULL.
-
If the string is empty, first{} throws an exception and firstOrNull{} returns NULL
6.1.2 firstOrNull() and firstOrNull{} functions
seek = ""
NoSuchElementException: Char sequence is empty.
// println(seek.first())
println(seek.firstOrNull())//null
// Returns null if the string is empty or there is no such character in the string
var foN= seek.firstOrNull {
it == 'N'
}
println(foN)//null
seek = "Note"
// Char =N
foN= seek.firstOrNull {
it == 'N'
}
println(foN)//N
Copy the code
6.2 Getting the last element
seek = "Note"
println(seek.last())//e
var la = seek.last {
it == 't'
}
println(la)//t
Copy the code
Similar firstOrNull lastOrNull () (). Similar firstOrNull lastOrNull {} {}.
6.3 Searching for Elements
-
IndexOf () : Finds the first occurrence of an element or string in the original string.
-
IndexOfFirst {} : with indexOf ().
-
LastIndexOf (): Finds the index of the last occurrence of an element or string in the original string.
-
IndexOfLast {} : with lastIndexOf ().
val cz = "Android|Java|Kotlin"
// find the first occurrence of I in cz.
println(cz.indexOf('i'))/ / 5
println(cz.indexOf("i"))/ / 5
// Find the subscript of the first occurrence of I in cz, starting at bit 10.
println(cz.indexOf("i".10))/ / 17
var z = cz.indexOfFirst {
it == 'i'
}
println(z)/ / 5
// find the last occurrence of I in cz.
println(cz.lastIndexOf('i'))/ / 17
println(cz.lastIndexOf("i"))/ / 17
// Find the subscript of the first occurrence of I in cz, starting at bit 10.
println(cz.lastIndexOf("i".10))/ / 5
z = cz.indexOfLast {
it == 'i'
}
println(z)/ / 17
Copy the code
String validation
In real development, especially Android development, it is often the case to verify that the content of the input field is an empty string.
The following functions handle empty or null strings:
- IsEmpty (): its source code determines whether its length is equal to 0, and returns true if it is equal to 0, and false if it is equal to 0. Cannot be used directly for nullable strings
- IsNotEmpty (): its source checks whether its length is greater than 0, and returns true if it is greater than 0, and false otherwise. Cannot be used directly for nullable strings
- IsNullOrEmpty (): The source checks whether the string is null or whether its length is equal to 0.
- IsBlank (): the source determines whether its length is equal to 0, or whether the number of Spaces it contains is equal to the current length. Cannot be used directly for nullable strings
- IsNotBlank (): the source is the inverse of isBlank(). Cannot be used directly for nullable strings
- IsNotOrBlank (): its source determines whether the string is null. Or call isBlank()
var verification = ""
println(verification)
println(verification.isEmpty())//true
println(verification.isNotEmpty())//false
println(verification.isNullOrEmpty())//true
println(verification.isBlank())//true
println(verification.isNotBlank())//false
println(verification.isNullOrBlank())//true
verification = "Kotlin"
println(verification)
println(verification.isEmpty())//false
println(verification.isNotEmpty())//true
println(verification.isNullOrEmpty())//false
println(verification.isBlank())//false
println(verification.isNotBlank())//true
println(verification.isNullOrBlank())//false
Copy the code
A hodgepodge
8.1 String Stitching
- Use the +
- Use the plus() function
var name = "ShuaiCi "
// String concatenation
println(name + "Return to early Sleep Artist")//ShuaiCi return early sleep artist
println(name.plus("It doesn't matter. Best actor."))//ShuaiCi doesn't have the best actor
println(name.plus(12.5))/ / ShuaiCi 12.5
Copy the code
8.2 Obtaining the String Length
- Get the length directly with the length attribute
- The count() function returns the length.
var name = "ShuaiCi "
// String length
println(name.length)/ / 8
println(name.count())/ / 8
Copy the code
8.3 Statistics repeat Characters
-
The count() function returns the length property to get the length of the string.
-
Count {} a higher-order function that counts the number of repeated characters in a string.
var name = "ShuaiCi "
// There are two I's in name
var coun = name.count {
it == 'i'
}
println(coun)/ / 2
Copy the code
8.4 String Inversion
Use the reversed() function to reverse the elements of a string.
println(name)//ShuaiCi
println(name.reversed())// iCiauhS
Copy the code
8.5 Determine the start and end of a string
8.5.1 Start: startsWith()
Determines whether the string starts with a character or a string.
var name = "ShuaiCi "
println(name.startsWith('S'))//true
println(name.startsWith("Shuai"))//true
println(name.startsWith("Ci"))//false
println(name.get(5))//C
// Whether to start with the string 'Ci' when position 5
println(name.startsWith("Ci".5))//true
Copy the code
8.5.2 Ending: endsWith()
Determines whether the string is terminated by a character or a string.
var name = "ShuaiCi "
println(name.endsWith(' '))//true
println(name.endsWith("Shuai"))//false
println(name.endsWith("Ci "))//true
Copy the code
8.6 go to space
Use the trim() function to return a string with the value of that string, removing any leading and trailing whitespace.
name = " ShuaiCi "
println(name)// ShuaiCi
println(name.trim())//ShuaiCi
var cun = name.trim {
it == ' '
}
println(cun)//ShuaiCi
Copy the code
8.7 String Templates
- Templates support enclosing variable values in quotes around strings.
- String embedded expression.
name = "Shuaici"
val age = 18
val money = 1.25 f
// Put variable values in quotes
//Shuaici is 18 years old and has a fortune of 1.25
println("$nameThis year,$ageI have it with me$moneyMoney. "")
val isMan = true
// Add an expression
//Shuaici is a man
println("$nameIs a${if (isMan) "All men." else "Cute girl."}")
Copy the code
8.8 String Traversal
name = "Shuaici"
name.forEach {
print("$it|")}Copy the code
8.9 String Type Conversion
var str = "12.5"
// Use toFloatOrNull to return null if STR is null or an empty string
// With toFloat, STR is null or an empty string returns an error: NumberFormatException
println(str.toFloatOrNull())/ / 12.5
str= ""
println(str.toFloatOrNull())//null
// println(str.toFloat())//NumberFormatException
var i = true
println(i.toString())//true
Copy the code
Other reference type conversions are similar.