DEV Community

Cover image for Strings in Kotlin
Jay Tillu😎
Jay Tillu😎

Posted on • Updated on

Strings in Kotlin

  • Strings are represented by String word.

  • Strings are immutable. Elements of a string are characters that can be accessed by the indexing operation: s[i].

  • Strings can be iterated over with a for-loop.

  • You can concatenate strings using the + operator. This also works for concatenating strings with values of other types, as long as the first element in the expression is a string or character.

  • You cannot perform a string concatenation operation if a first element in the expression is Number or Boolean.

val s = “Hello” + 1234
val s = “Hello” + 11.14
val s = “Hello” + ‘J’
val s =   ‘J’    + “Hello”
val s = “Hello” + true

val s = 1234   +  “Hello”    //Compile time error.
val s = 43.24  +  “Hello”    //Compile time error.
val s = true   +  “Hello”    //Compile time error.
Enter fullscreen mode Exit fullscreen mode
  • Note that in most cases using string template or raw strings is preferable to string concatenation.

String Literals


Kotlin has two types of string literals:

  1. Escaped strings
  2. Raw strings

Escaped String

  • Escaped strings — They may have escaped characters in them. The escaped string is very much like a java string.
val s = “Hello World \n”
Enter fullscreen mode Exit fullscreen mode
  • Escaping is done in a conventional way, with a backslash.

Raw String

  • Raw strings — Raw strings that contain newlines and arbitrary text.
  • A raw string delimited by a triple quote (“ ” ”), contains no escaping and you can contain newlines and any other characters:
val text = """ This is a Example
       Look How concise it is
       That is the magic of kotlin
"""
Enter fullscreen mode Exit fullscreen mode
  • trimMargin() is a recommended way for indentation in a raw string.
val text = """
       | Tell me and I forgot.
       | Teach me and I remember.
       | Involve me and I learn.
       | (Benjamin Franklin)
    """.trimMargin()
Enter fullscreen mode Exit fullscreen mode
  • By default | is used as a margin prefix, but you can choose another character and pass it as a parameter, like trimMargin(">"). You can also use trimIndent().

  • If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:

val price = """
${'$'}9.99
"""
Enter fullscreen mode Exit fullscreen mode

So, guys, that’s it for strings in kotlin. Feel free to let me know if I missed something.

Till then Keep Coding, Keep Loving. Catch you up in another article.

Jai Hind, Vande Mataram 🇮🇳

Wanna get in touch with me? Here are links. I’ll love to become your friend. 😊

Top comments (0)