loading...
Cover image for Strings in Kotlin

Strings in Kotlin

jay_tillu profile image Jay Tillu😎 ・2 min read
  • 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.
  • 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”
  • 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
"""
  • 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()
  • 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
"""

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.

Wanna get in touch with me? Here are links. I’ll love to become your friend. 😊
Twitter
Facebook
Instagram
Medium
or just mail me at jayviveki13@gmail.com

Posted on by:

jay_tillu profile

Jay Tillu😎

@jay_tillu

🌏 विधायास्य धमॅस्य संरक्षणम् 🌍 ☀️ Society before Self ☀️ 🙏🏻 Humanism by Religion 🙏🏻 💻 Work for Mankind 💻 🌐 Believes in वसुधैव कुटुम्बकम् 🌐

Discussion

pic
Editor guide