Kotlin 简明教程

Kotlin - Strings

Kotlin String 数据类型用于存储一系列字符。字符串值必须用双引号 (“ ”) 或三引号 (""" """) 括起来。

The Kotlin String data type is used to store a sequence of characters. String values must be surrounded by double quotes (" ") or triple quote (""" """).

在 Kotlin 中,我们有两种字符串 - 一种称为 Escaped String ,另一种称为 Raw String

We have two kinds of string available in Kotlin - one is called Escaped String and another is called Raw String.

  1. Escaped string is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' etc.

  2. Raw string is declared within triple quote (""" """) and may contain multiple lines of text without any escape characters.

Example

fun main(args: Array<String>) {
   val escapedString : String  = "I am escaped String!\n"
   var rawString :String  = """This is going to be a
   multi-line string and will
   not have any escape sequence""";

   print(escapedString)
   println(rawString)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

I am escaped String!
This is going to be a
   multi-line string and will
   not have any escape sequence

为字符串指定数据类型是可选的,Kotlin 能够因为给定的双引号或三引号而理解变量是一个字符串。

This is optional to specify the data type for a String, Kotlin can understand that the a variable is a String because of the given double or tripple quotes.

如果您想创建未赋值的字符串变量,则您必须在声明该变量的同时指定类型,否则会引发错误:

If you want to create a String variable without assigning the value then you must specify the type while declaring the variable otherwise it will raise an error:

fun main(args: Array<String>) {
   val name : String

   name = "Zara Ali"

   println(name)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Zara Ali

Kotlin String Templates

Kotlin 字符串模板是经过评估的代码片段,其结果插入到字符串中。模板表达式以美元符号 ($) 开始,并可能包含名称或表达式。

Kotlin string templates are pieces of code that are evaluated and whose results are interpolated into the string. A template expression starts with a dollar sign ($) and may consist of either a name or an expression.

fun main(args: Array<String>) {
   val name : String = "Zara Ali"

   println("Name  - $name")  // Using template with variable name

   println("Name length - ${name.length}")  // Using template with expression.
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Name - Zara Ali
Name length - 8

Kotlin String Object

Kotlin 字符串是一个对象,它包含许多可以对字符串执行特定操作的属性和函数,方法是在特定字符串变量后写上一个点字符 (.)。

Kotlin String is an object, which contains a number of properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable.

我们将在本章中看到一些重要的属性和函数,剩下的可以在 Kotlin 最新版本的官方文档中找到。

We will see some of the important properties and functions in this chapter, remaining you can find in official documentation of Kotlin latest version.

Kotlin String Indexes

Kotlin 字符串可以被视为一系列字符,或者可以说字符串是一个字符数组。您可以通过使用方括号指定元素的索引来访问其元素。

Kotlin String can be treated as a sequence of characters or you can say String is an array of characters. You can access its element by specifying the index of the element using a square brackets.

字符串索引从 0 开始,所以如果您想访问字符串的第 4 个元素,那么您应将索引指定为 3 才能访问第 4 个元素。

String indexes start with 0, so if you want to access 4th element of the string then you should specify index as 3 to access the 4th element.

Example

fun main(args: Array<String>) {
   val name : String = "Zara Ali"

   println(name[3])
   println(name[5])
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

a
A

Kotlin String Length

我们可以使用 Kotlin 字符串的 length 属性来找出其长度。

We can use length property of Kotlin string to find out its length.

Kotlin 函数 count() 也返回给定字符串的长度。

Kotlin function count() also returns the length of a given string.

Example

fun main(args: Array<String>) {
   val name : String = "Zara Ali"

   println("The length of name :" + name.length)
   println("The length of name :" + name.count())

}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

The length of name :8
The length of name :8

Kotlin String Last Index

我们可以使用 Kotlin 字符串的 lastIndex 属性来找出字符序列中最后一个字符的索引。如果字符串为空,则返回 -1。

We can use lastIndex property of Kotlin string to find out the index of the last character in the char sequence. If a string is empty then it returns a -1.

Example

fun main(args: Array<String>) {
   val name : String = "Zara Ali"

   println("The index of last character in name :" + name.lastIndex)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

The index of last character in name :7

Changing Case of Strings

Kotlin 提供 toUpperCase()toLowerCase() 函数分别将字符串转换为大写和小写。

Kotlin provides toUpperCase() and toLowerCase() functions to convert a string into upper case and lower case respectively.

Example

fun main(args: Array<String>) {
   val name : String = "Zara Ali"

   println("Upper case of name :" + name.toUpperCase())
   println("Lower case of name :" + name.toLowerCase())
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Upper case of name :ZARA ALI
Lower case of name :zara ali

Kotlin String Concatenation

我们可以使用 + 运算符将两个字符串连接起来,也可以使用 plus() 函数将两个字符串连接起来。

We can use either + operator to concatenate two strings, or we can also use plus() function to concatenate two strings.

Example

fun main(args: Array<String>) {
   var firstName : String = "Zara "
   var lastName : String = "Ali"

   println("Full Name :" + firstName + lastName)

   println("Full Name :" + firstName.plus(lastName) )
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Full Name :Zara Ali
Full Name :Zara Ali

Trim Characters from a String

我们可以使用 drop()dropLast() 函数从字符串中移除最前面的几个或最后的几个字符。

We can remove first few or last few characters from a string using drop() or dropLast() functions.

Example

fun main(args: Array<String>) {
   var name : String = "Zara Ali"

   println("Remove first two characters from name : " + name.drop(2))

   println("Remove last two characters from name : " + name.dropLast(2))
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Remove first two characters from name : ra Ali
Remove last two characters from name : Zara A

Quotes Inside a String

要在字符串内使用引号,请使用单引号 ('):

To use quotes inside a string, use single quotes ('):

Example

fun main(args: Array<String>) {
   var str1 : String = "That's it"
   var str2 : String = "It's OK"

   println("str1 : " + str1)
   println("str2 : " + str2)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

str1 : That's it
str2 : It's OK

Finding a String inside a String

Kotlin 提供 indexOf() 函数来找出字符串中的文本。该函数返回字符串中首次出现指定文本的索引

Kotlin provides indexOf() function to find out a text inside a string. This function returns the index of the first occurrence of a specified text in a string

Example

fun main(args: Array<String>) {
   var str : String = "Meditation and Yoga are synonymous with India"

   println("Index of Yoga in the string - " + str.indexOf("Yoga"))
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Index of Yoga in the string - 15

Comparing Two Strings

Kotlin 提供 compareTo() 函数来比较两个字符串。如果两个字符串相等,则该函数返回 0,否则返回 1。

Kotlin provides compareTo() function to compare two strings. This function returns 0 if two strings are equal otherwise it will return 1.

Example

fun main(args: Array<String>) {
   var str1 : String = "Apple"
   var str2 : String = "Apple"

   println(str1.compareTo(str2))
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

0

Kotlin getOrNull() function

Kotlin getOrNull() 函数返回给定索引处的字符,如果该索引超出了此字符序列的界限,则返回 null。

Kotlin getOrNull() function returns a character at the given index or null if the index is out of bounds of this char sequence.

Example

fun main(args: Array<String>) {
   var name : String = "Zara"

   println(name.getOrNull(0))
   println(name.getOrNull(2))
   println(name.getOrNull(100))
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Z
r
null

Kotlin toString() function

Kotlin toString() 函数返回对象的字符串表示。

Kotlin toString() function returns a string representation of the object..

Example

fun main(args: Array<String>) {
   var name : String = "Zara Ali"

   println(name.toString())
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Zara Ali