📜  Kotlin字符串

📅  最后修改于: 2021-01-05 07:29:38             🧑  作者: Mango

科特林弦

String类表示char类型的数组。字符串是不可变的,这意味着长度和元素在创建后无法更改。

val ch = charArrayOf('h', 'e', 'l', 'l', 'o')
    val st = String(ch)

与Java不同,Kotlin不需要新的关键字来实例化String类的对象。可以简单地在称为转义字符串的双引号(“”)或称为原始字符串的三重引号(“”“”“”“)中声明字符串。

val str1 = "Hello, javaTpoint"
val str2 = """Welcome To JavaTpoint"""

Kotlin String属性

Property Description
length: Int It returns the length of string sequence.
indices: IntRange It returns the ranges of valid character indices from current char sequence.
lastIndex: Int It returns the index of last character from char sequence.

字符串功能

Functions Description
compareTo(other: String): Int It compares the current object with specified object for order. It returns zero if current is equals to specified other object.
get(index: Int): Char It returns the character at given index from the current character sequence.
plus(other: Any?): String It returns the concatenate string with the string representation of the given other string.
subSequence(startIndex: Int,endIndex: Int): CharSequence It returns the new character sequence from current character sequence, starting from startIndex to endIndex.
CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false):Boolean It returns true if the character sequence contains the other specified character sequence.
CharSequence.count(): Int It returns the length of char sequence.
String.drop(n: Int): String It returns a string after removing the first n character.
String.dropLast(n: Int): String It returns a string after removing the last n character.
String.dropWhile
(predicate: (Char) -> Boolean
): String
It returns a character sequence which contains all the characters, except first characters which satisfy the given predicate.
CharSequence.elementAt(index: Int): Char It returns a character at the given index or throws an IndexOutOfBoundsException if the index does not exist in character sequence.
CharSequence.indexOf(char: Char, startIndex: Int = 0,
ignoreCase: Boolean = false
): Int
It returns the index of first occurrence of the given character, starting from the given index value.
CharSequence.indexOfFirst(
predicate: (Char) -> Boolean
): Int
It returns the index of first character which match the given predicate, or -1 if the character sequence not contains any such character.
CharSequence.indexOfLast(
predicate: (Char) -> Boolean
): Int
It returns the index of last character which match the given predicate, or -1 if the character sequence not contains any such character.
CharSequence.getOrElse(index: Int, defaultValue: (Int) ->Char): Char It returns the character at specified index or the result of calling the defaultValue function if the index is out of bound of current character sequence.
CharSequence.getOrNull(index: Int): Char? It returns a character at the given index or returns null if the index is out of bound from character sequence.

字符串元素和模板

字符串元素

这是目前在字符串中的字符被称为字符串的元素。通过索引操作字符串[index]访问字符串的元素。字符串的索引值从0开始,以小于字符串字符串[字符串 .length-1]的大小结尾。索引0代表第一个元素,索引1代表第二个元素,依此类推。

val str ="Hello, javatpoint"
println(str[0]) //prints H

访问字符串元素的示例

fun main(args: Array) {

val str = "Hello, javatpoint!"
println(str[0])
println(str[1])
println(str[str.length-1])
}

输出:

H
e
!

字符串模板

字符串模板表达式是一段经过评估的代码,其结果返回到字符串。两种字符串类型(转义和原始字符串)都包含模板表达式。字符串模板以美元符号$开头,美元符号由变量名或大括号中的任意表达式组成。

字符串模板作为变量名:

val i =10
print("i = $i") //i=10

fun main(args: Array) {
val i =10
    print("i = $i")//i=10
}

输出:

i=10

字符串模板作为花括号中的任意表达式:

字符串模板还用于花括号中的任意表达式中,以求值字符串表达式。这是通过使用美元符号$来完成的。

fun main(args: Array) {
val str = "abc"
println("$str is a string which length is ${str.length}")
}
abc is a string which length is 3

原始字符串的字符串模板:

fun main(args: Array) {
val a = 10
val b = 5

val myString = """value $a
        |is greater than value $b
    """.trimMargin()
println("${myString.trimMargin()}")
}

输出:

value 10
is greater than value 5

Kotlin字符串字面量

Kotlin有两种类型的字符串字面量:

  • 转义字符串
  • 原始字符串

转义字符串

转义字符串在双引号(“”)中声明,并且可以包含转义字符,例如'\ n','\ t','\ b','\ r','\ $'等。

val text1 ="Hello, JavaTpoint"
//or
val text2 ="Hello, JavaTpoint\n"
//or
val text3 ="Hello, \nJavaTpoint"

原始字符串

行字符串在三引号(“”“”“”)中声明。它提供了在新行中声明String并包含多行的功能。行字符串不能包含任何转义字符。

val text1 ="""
             Welcome 
                 To
JavaTpoint
    """

在新行中使用原始字符串时,它会生成一个|。作为保证金前缀。例如:

fun main(args: Array) {

val text = """Kotlin is official language
        |announce by Google for
        |android application development
    """
println(text)
}

输出:

Kotlin is official language
        |announce by Google for
        |android application development

字符串trimMargin()函数

可以使用trimMargin()函数删除前导空格。默认情况下,trimMargin()函数使用|。作为保证金前缀。

fun main(args: Array) {

val text = """Kotlin is official language
        |announce by Google for
        |android application development
    """.trimMargin()

println(text)
}

输出:

Kotlin is official language
announce by Google for
android application development

但是,可以通过在trimMargin()函数内部传递新字符串来更改它。

fun main(args: Array) {

val text = """Kotlin is official language
        #announce by Google for
        #android application development
    """.trimMargin("#")
println(text)
}

输出:

Kotlin is official language
announce by Google for
android application development

Kotlin字符串平等

在Kotlin中,字符串相等性比较是基于结构相等性(==)和引用相等性(===)进行的。

在结构相等中,两个对象在内存中具有单独的实例,但包含相同的值。

引用相等性指定两个不同的引用指向内存中的同一实例。

结构相等(==)

要检查两个包含相同值的对象,我们使用==运算符或!=运算符进行求反。它等效于Java中的equals()

fun main(args: Array) {
val str1 = "Hello, World!"
val str2 = "Hello, World!"
println(str1==str2) //true
println(str1!=str2) //false
}

输出:

true
false

参照相等(===)

为了检查指向同一实例的两个不同引用,我们使用===运算符。 !==运算符用于求反。当且仅当a和b都指向同一个对象时,a === b才指定true。

让我们看一个引用相等的示例,以检查不同的引用是否包含相同的实例。为了创建字符串,我们使用辅助方法buildString而不是引号。

fun main(args: Array) {
val str1 = buildString { "string value" }
val str2 = buildString { "string value" }
println(str1===str2)
println(str1!==str2)
}

输出:

false
true