Kotlin String Datatype

Strings are groups of characters enclosed in double quotes. variable declared with a String type to store a group of characters.

Here is an example

val str="Hello"  // Implicit Conversion
val str: String= "hello" // Explicit Conversion

Each string contains a group of characters.

Strings are immutable, Once a string object is created, the value is not changed by any operation, It creates a new string.

For example,

String object created with string literal, It creates an object.

  • Calling str.lowercase() method converts the existing string into lower case string. Here, It creates another string with lowercase.

  • Total two string objects created with a single operation.

val str = "GHIJ"
println(str.lowercase()) // Create a new String object with lower case
println(str)  // original string returns and printed.

Another example with string immutable

Below example,

  • Creates two string objects - one and two
  • Another string is created by appending two strings. It creates a third string.
  • Total three strings created.
val s = "one" + " two"
println(s)

How to declare String literal in Kotlin

String literals can be of two types

  • Escaped String literal

String literals can be declared with escape characters as defined.

The below example contains the \n new line escape character.

fun main() {
    val str = "Hello, \n Welcome to my world\n"
    println(str)
}

It prints

Hello,
 Welcome to my world

How to declare and assign Raw multi-line Strings in KOTLIN

Raw Strings is a multi-line string that contains unprocessed content enclosed in triple quotes.

Raw String literal contains

  • String content in multiple lines enclosed in triple quotes(""")
  • No escape characters allowed
  • Pipe symbol is used as a marker for removing space when using trimMargin() function
  • Template variables can be used.
fun main() {
val text = """
    |line 1.
    |line 2.
    |line 3.
    |line 4.
    """.trimMargin()
    println(text)
}

Output:

line 1.
line 2.
line 3.
line 4.

Below example uses _ as a marker for removing whitespaces when using trimMargin("_")

fun main() {
val text = """
    _line 1.
    _line 2.
    _line 3.
    _line 4.
    """.trimMargin("_")
    println(text)
}

Output:

line 1.
line 2.
line 3.
line 4.

Some example Raw Strings are HTML DOM tree string

String template Syntax examples

String template contains expressions or variables, executed and append its value at runtime.

Expressions start with $ followed by a name enclosed in {}.

Syntax

" string literal  ${variable}"

Template syntax is used in Raw literals as well as escape string syntax literal.

Here is an example

fun main() {
    val age= 25
    val s = "Hello, My age is ${age}"
    println(s)
    val website= "abccc.com"
    val str = "Hello, \n Welcome to my ${website}\n"
    println(str)
}

Output:

Hello, My age is 25
Hello,
 Welcome to my abccc.com