kotlin_Kotlin弦
kotlin
In this tutorial, we’ll be discussing at length an important data type of Kotlin, namely Kotlin String. It’s recommended to read Introduction to Kotlin tutorial before proceeding ahead.
在本教程中,我们将详细讨论Kotlin的一种重要数据类型,即Kotlin String。 建议先阅读Kotlin入门教程,然后再继续。
Kotlin弦 (Kotlin String)
String is an array of characters. Kotlin Strings are more or less similar to the Java Strings, but with some new add-ons. Following is the syntax to define a string.
字符串是字符数组。 Kotlin字符串或多或少类似于Java字符串,但带有一些新的附加组件。 以下是定义字符串的语法。
var str: String = "Hello"
//or
var str = "Hello"
var newString: String = 'A' //ERROR
var newString: String = 2 //ERROR
String in Kotlin is implemented using the String class. Like Java String, Kotlin Strings are immutable.
Kotlin中的String是使用String类实现的。 像Java String一样,Kotlin Strings是不可变的。
var str = "Hello"
str += "Kotlin Strings"
The above declaration changes the reference of the variable str in the second line to the newly created string(“Hello Kotlin Strings”) in the String Pool.
上面的声明将第二行中变量str的引用更改为String Pool中新创建的字符串(“ Hello Kotlin Strings”)。
Creating an empty String
创建一个空字符串
var s = String() //creates an empty string.
Unlike Java, Kotlin doesn’t require a new keyword to instantiate an object of a class.
与Java不同,Kotlin不需要new关键字来实例化类的对象。
Kotlin弦的重要属性和功能 (Important Properties and Functions of Kotlin String)
length: This is a property that can be accessed using the dot operator on the String. Returns the number of characters present in a string.val str = "Hello Kotlin Strings" println(str.length) //prints 20length:这是一个属性,可以使用String上的点运算符进行访问。 返回字符串中存在的字符数。get(index): Returns the character specified at the particular index.get(index):返回在特定索引处指定的字符。subSequence(startIndex, endIndex): Returns the substring between thestartIndexand theendIndexbut excluding the endIndex character.val str = "Hello Kotlin Strings" println(str.subSequence(0,5)) //prints HellosubSequence(startIndex, endIndex):返回介于startIndex和endIndex之间的子字符串,但不包括endIndex字符。a.compareTo(b): If a is equal to b, it returns 0, if a<b it returns positive number. compareTo accepts another argument too, namelyignoreCase.var str = "Hello Kotlin Strings" var s = String() s = "Hello KOTLIN Strings" println(s.compareTo(str)) //prints -32 println(s.compareTo(str,true)) //prints 0a.compareTo(b):如果a等于b,则返回0,如果a <b,则返回正数。 compareTo也接受另一个参数,即ignoreCase。
访问字符串中的字符 (Accessing Characters in a String)
To access individual characters of a String, Kotlin supports the index access operator(Unlike Java) as shown below.
Using Index Operator
要访问String的各个字符,Kotlin支持索引访问运算符(不同于Java),如下所示。
使用索引运算符
var str = "Hello, Kotlin"
print(str[0]) //prints H
Using the get method
使用get方法
val str = "Hello Kotlin Strings"
println(str.get(4)) //prints o
Iterating through a String
We can loop through a string to access each character using a for-in loop as shown below.
遍历字符串
我们可以使用for-in循环遍历字符串以访问每个字符,如下所示。
for(element in str){
println(element)
}
Kotlin字符串中的转义字符 (Escape characters in Kotlin Strings)
Following are the escape characters that when used with a backslash behave differently.
以下是与反斜杠一起使用时的转义字符,其行为有所不同。
\nnewline.\n换行符。\rcarriage return.\r回车。\ttab.\t标签。\bbackspace\b退格键\"double quote\"双引号\'single quote\'单引号\\backslash\\反斜杠\$dollar – Dollar symbol is used in String templates that we’ll be seeing next\$dollar –在字符串模板中使用美元符号,我们接下来将看到字符串模板 (String Templates)
Instead of concatenating an expression in a string, Strings can contain expressions/statements following a dollar symbol as shown below.
代替在字符串中连接表达式,字符串可以包含在美元符号后面的表达式/语句,如下所示。
var len = str.length var newStr = "Length of str is ${str.length}" //or var newStr = "Length of str is $len" println(Length of str is ${str.length})Using string templates, we can insert variables and expressions in a string. String Templates are commonly used in
printstatements.
To use the $ symbol in a string we need to escape the character.使用字符串模板,我们可以在字符串中插入变量和表达式。 字符串模板通常在
print语句中使用。
要在字符串中使用$符号,我们需要对字符进行转义。var escapedDollar = "Amount is \$5.50" print(escapedDollar) //prints Amount is $5.50原始字符串–多行字符串 (Raw Strings – Multiline String)
Raw strings are strings placed inside triple quotes. We don’t have to escape characters in triple-quoted strings. These strings can be used in multi lines without the need to concatenate each line.
原始字符串是放在三重引号内的字符串。 我们不必用三引号引起来的字符转义。 这些字符串可以在多行中使用,而无需连接每行。
var rawString = """Hi How you're Doing I'm doing fine. I owe you $5.50""" print(rawString) //Prints the following in the console Hi How you're Doing I'm doing fine. I owe you $5.50Note: Since escape characters are not parsed, adding a \n or \t won’t have any effect.
注意 :由于未解析转义字符,因此添加\ n或\ t不会有任何效果。
var rawString = """Hi How you're Doing I'm doing fine\n. I owe you $5.50""" print(rawString) //prints the following Hi How you're Doing I'm doing fine\n. I owe you $5.50Raw strings are handy when you need to specify a file/directory path in a string.
We can indent raw strings or remove the whitespacing in multi-lines using the functiontrimMargin().当您需要在字符串中指定文件/目录路径时,使用原始字符串非常方便。
我们可以使用函数trimMargin()缩进原始字符串或多行删除空格。var rawString = """Hi How you're Doing |I'm doing fine. |I owe you $5.50""".trimMargin("|") print(rawString) //Prints the following to the console. Hi How you're Doing I'm doing fine. I owe you $5.50Note: We can’t pass a blank string as the trim margin. The
trimMargin()function trims the string till the marginPrefix specified.注意:我们不能传递空白字符串作为修剪边距。
trimMargin()函数将字符串修剪到指定的marginPrefix为止。String templates and Raw Strings can be combined together as shown below.
字符串模板和原始字符串可以组合在一起,如下所示。
var str = "Kotlin" var rawString = """Hi How you're Doing $str |I'm doing fine. |I owe you $5.50""".trimMargin("|") print(rawString) //The following gets printed on the console Hi How you're Doing Kotlin I'm doing fine. I owe you $5.50覆盖字符串方法 (Overriding String method)
In Java, we commonly override toString() method of a class to display the contents of the class’s instance object. Similar stuff happens in Kotlin too as shown below.
在Java中,我们通常重写类的toString()方法以显示该类的实例对象的内容。 如下所示,在Kotlin中也发生了类似的事情。
class Student(var name: String, var age: Int) { //Define properties and functions here. } //The following code is written inside the main function of the Kotlin class. var student = Student("Anupam", 23) print(student) //prints com.journaldev.Strings.Student@34a245abPrinting the above object doesn’t give any idea about the variables initialised.
Here’s where we override thetoString()method as shown below.打印上面的对象不会对初始化的变量有任何想法。
此处是我们重写toString()方法的地方,如下所示。class Student(var name: String, var age: Int) { override fun toString(): String { return "Student name is $name and age is $age" } } //The following code is written inside the main function of the Kotlin class. var student = Student("Anupam", 23) print(student) //prints Student name is Anupam and age is 23Note: Unlike Java, Kotlin doesn’t require a
newkeyword to initialize the constructor of a class.注意 :与Java不同,Kotlin不需要
new关键字即可初始化类的构造函数。字符串相等 (String Equality)
There are two types of equality checkers.
有两种类型的相等性检查器。
- Referential Equality: Checks if the pointers for two objects are the same.
===operator is used. 引用相等 :检查两个对象的指针是否相同。===运算符。 - Structural Equality : Checks if the contents of both the objects are equal.
==is used. 结构相等 :检查两个对象的内容是否相等。==被使用。
Following code snippet demonstrates the above checkers.
以下代码段演示了上述检查器。
var a = "Hello" var b = "Hello again" var c = "Hello" var d1 = "Hel" var d2 ="lo" var d = d1 + d2 println(a===c) // true since a and c objects point to the same String in the StringPool println(a==c) //true since contents are equal println(a===b) //false println(a==b) //false println(a===d) //false since d is made up of two different Strings. Hence a and d point to different set of strings println(a==d) //true since the contents are equalNote: The negation of === and == are !=== and !== respectively.
注意:===和==的取反分别是!===和!==。
This brings an end to kotlin string tutorial.
这样就结束了kotlin字符串教程。
kotlin
- Referential Equality: Checks if the pointers for two objects are the same.
更多推荐


所有评论(0)