kotlin strings

Kotlin String

In this post, you will learn about Kotlin string, String Literals, Elements for String, and String Templates with the help of examples.

Kotlin String

String Equality. In Kotlin string are compared with == operator which check for their structural equality.

val str1 = "Hello, World!"
val str2 = "Hello," + " World!"
println(str1 == str2) // Prints true

Referential equality is checked with === operator.

val str1 = """
|Hello, World!
""".trimMargin()
val str2 = """
#Hello, World!
""".trimMargin("#")
val str3 = str1
println(str1 == str2) // Prints true
println(str1 === str2) // Prints false
println(str1 === str3) // Prints true

Kotlin String Literals

Kotlin has two types of string literals:

  • Escaped string
  • Raw string

Escaped string handles special characters by escaping them. Escaping is done with a backslash. The following escape sequences are supported: \t, \b, \n, \r, \’, \”, \\ and \$. To encode any other character, use the Unicode escape sequence syntax: \uFF00.

val s = "Hello, world!\n"

Raw string delimited by a triple quote “””, contains no escaping and can contain newlines and any other characters

val text = """
for (c in "foo")
print(c)
"""

Leading whitespace can be removed with trimMargin() function.

val text = """
|Tell me and I forget.
|Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
""".trimMargin()

Default margin prefix is pipe character |, this can be set as a parameter to trimMargin; e.g. trimMargin(“>”).


Kotlin String Elements

Elements of String are characters that can be accessed by the indexing operation string[index].

val str = "Hello, World!"
println(str[1]) // Prints e

String elements can be iterated with a for-loop.

for (c in str) {
println(c)
}

Kotlin String Templates

Template expressions can be found in both escaped and raw strings. A string is created by concatenating the results of a string template expression, which is a piece of code that is evaluated. Starting with the dollar sign $, it consists of one of the following variable names:

val i = 10
val s = "i = $i" // evaluates to "i = 10"

Or an arbitrary expression in curly braces:

val s = "abc"
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"

To include a literal dollar sign in a string, escape it using a backslash:

val str = "$foo" // evaluates to "$foo"

The exception is raw strings, which do not support escaping. In raw strings you can use the following syntax to another represent a dollar sign.

val price = """
${'$'}9.99
"""

Also read : Kotlin Tutorial for Beginners