New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL
See the Tutorial List

Kotlin String

In this tutorial we will introduce you to Kotlin Strings, covering the Kotlin String class, its properties and functions with code examples.

A string is an array of characters combined together. Strings are usually created using double quotes "". We can also create multi-line string using triple quotes """. This string is also known as raw string.

A basic example of string is "Studytonight", or "Studytonight123", etc. are strings. Internally, it is treated as array of characters, which you will understand as we will cover some code examples.

Similar to Java, strings are immutable in nature. By immutable, it doesn't mean that we cannot change value of a string variable. It means that whenever we change the value of a string, instead of changing that instance of the string, compiler creates a new instance of the string.

Let us understand it with an example:

fun main() {
    var string: String = "Hello"
    string = "Bye"
    println(string)
}

Here on line 2, we created a variable string and assigned "Hello" value to it. The compiler will create a new string in the String pool. Now when we assign "Bye" to string, the compiler will again create a new string, store it in String pool and assign its instance to the string variable. And the previously created string "Hello" will still be present in the string pool.

Properties and Methods of String class

The String class contains many properties and methods which are used to manage Kotlin strings and perform operations on it. Some important properties and functions are:

Kotlin String Properties:

  • length: Represents the length of string.

  • lastIndex: Represents the index of last character in string.

Kotlin String Methods:

  • get(index): Returns the character at the specified index in the string or throws IndexOutOfBoundsException.

  • first(): Returns first character in the string or throws NoSuchElementException if string is empty.

  • last(): Returns last character in the string or throws NoSuchElementException if string is empty.

  • plus(string): Returns a new string obtained by concatenating the string on which this method is called with the string given as parameter. It will not change the actual string as strings are immutable.

  • subSequence(startIndex, endIndex): Returns a sub sequence between the startIndex (inclusive) and endIndex (exclusive).

  • contains(subString, ignoreCase): Returns true if this string contains the given sub string in it. The ignoreCase parameter is as true/false to specify whether to ignore case or not.

  • capitalize(): Returns a copy of this string having its first letter uppercased.

  • decapitalize(): Returns a copy of this string having its first letter lowercased.

  • reversed(): Returns a string with characters in reversed order.

  • toLowerCase(): Returns a copy of this string converted to lower case.

  • toUpperCase(): Returns a copy of this string converted to upper case.

Let us use thesem methods and properties in an example:

fun main() {
    var message = "Hello World!!"
    // Properties
    println("Length of string: ${message.length}")
    println("Last index number: ${message.lastIndex}")

    // Functions
    println("Character at index 0: ${message[0]}")
    println("Character at index 1: ${message.get(1)}")
    println("First character in string: ${message.first()}")
    println("Last character in string: ${message.last()}")

    println("Add Bye to message for printing: ${message.plus(" Bye")}")
    println("Subsequence from message: ${message.subSequence(0,5)}")
    println("Message contains 'll'?: ${message.contains("ll")}")

    println("Capitalize message: ${message.capitalize()}")
    println("decapitalize message: ${message.decapitalize()}")
    println("Reversed message: ${message.reversed()}")
    println("Message in lower case: ${message.toLowerCase()}")
    println("Message in upper case: ${message.toUpperCase()}")

}


Length of string: 13
Last index number: 12
Character at index 0: H
Character at index 1: e
First character in string: H
Last character in string: !
Add Bye to message for printing: Hello World!! Bye
Subsequence from message: Hello
Message contains 'll'?: true
Capitalize message: Hello World!!
decapitalize message: hello World!!
Reversed message: !!dlroW olleH
Message in lower case: hello world!!
Message in upper case: HELLO WORLD!!

Do not get confused by the syntax ${ .. }, it is used to append a variable value to the println output in Kotlin.

String Template

We can add a piece of code and concatenate it to the string (after converting it into string). This piece of code is known as string template. We have used string template in printing values using println() function also. String template starts with a $ (dollar) symbol.

Let us see an example in which we will add a string template:

fun main() {
    var message = "Hello World!!"
    var multiLineMessage = """Adding message in
         multiline
         comment: 
         $message
    """
    println(multiLineMessage)
}


"Adding message in
multiline
comment:
Hello World!!

As you can see in the code above, we have added a string to the message that we printed in the println method using the $ symbol. This is very helpful when we are printing outputs with variables having string values.

Summary

In this tutorial we discussed about Kotlin Strings, its properties and methods. Strings are very useful when we are writing actual programs and all these methods will come in handy when you will work on developing your Android App using Kotlin. In the next tutorial we will discuss about Kotlin Arrays.