String in Kotlin

In this tutorial, we will learn about String in Kotlin. A string is an array of characters(char type values) and String class is used to represent strings in Kotlin. It is important to note just like Java, String is an immutable class in Kotlin it means we can not change of object once after creation.

Creating a String in Kotlin:

In Kotlin we can use double quotes (“”) to create escaped string or triple quote(“”” “””) to create raw string literals. Check out the following example program to understand different ways to create a string in Kotlin.

Example Program:

fun main(args : Array<String>){

    var str1 = "Owlbuddy" 
    var str2 = """Owlbuddy 
                  Programming 
                  Tutorials""" 
    var str3 : String = "Owlbuddy Programming Tutorials"
    var charArray= charArrayOf('O', 'w', 'l', 'b', 'u', 'd', 'd', 'y')  
    var str4 = String(charArray)  
    
    println(str1)
    println(str2)
    println(str3)
    println(str4)
}

Output:

Owlbuddy
Owlbuddy 
                  Programming 
                  Tutorials
Owlbuddy Programming Tutorials
Owlbuddy

Ways to create String in Kotlin:

  • using double quotes (“”)
  • and using triple quote(“”” “””)

Using double quotes (“”):

Most of the time we use double quotes to declare String literals in Kotlin. When we create double quotes to create Strings this kind of stings are known as escaped strings because we can use escape characters like ‘\n’, ‘\t’, ‘\b’, etc’ in these(double-quoted) strings. Please check out the example Program to understand it.

Example Program:

fun main(args: Array<String>) { 
      
    var name = "Rahul"
    var age = 20
    println("Hello $name \nYour age is $age") 
} 

Output:

Hello Rahul 
Your age is 20

Available Escape characters in Kotlin:

  • \”: to add a double quote in the string
  • \r: to carriage return
  • \n: to add a new line
  • \’: to add a single quote in the string
  • \\: to add a backslash in the string
  • \t: to add space in string
  • \b: to add backspace

Using the triple quote(“”” “””):

Another way to declare strings in Kotlin is by using triple quotes. Triple quotes are used to create raw strings. These are mainly used to create multi-line strings and raw strings can not contain escaped characters. Please check out the following example program to understand it.

Example Program:

fun main(args: Array<String>) { 
      
    var text="""Hello Friends
    |Welcome to Owlbuddy, You can Learn Here
    |Python
    |Java 
    |Kotlin etc""".trimMargin() 
    println(text) 
} 

In above example we have used trimMargin() function. This function is used to fix the margins in strings and it use | as margin prefix

Output:

Hello Friends
Welcome to Owlbuddy, You can Learn Here
Python
Java 
Kotlin etc

Empty String in Kotlin:

It is really easy to create an empty string in Kotlin. We just have to create an object of string class with default constructor to create an empty string. Please check out the following example program to understand it.

fun main(args : Array<String>){
    var str1 = String()
}

String Functions:

Functions Description
compareTo(other: String): Int This function is used to compare the current string object with the specified string object. It returns zero if the current string object equals to a specified string object.
get(index: Int): Char This function returns the character at the specified index in the string.
plus(other: Any?): String This function returns string after concatenating a string with the specified string.
subSequence(startIndex: Int,endIndex: Int): CharSequence This function returns the new string from the current string, starting from startIndex to endIndex.
CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false):Boolean This function returns true or false based on if the string contains the other specified character sequence.
CharSequence.count(): Int This function returns the length of the string.
String.drop(n: Int): String This function returns a string after removing the first n character from the string.
String.dropLast(n: Int): String This function returns a string after removing the last n character from the string.
String.dropWhile
(predicate: (Char) -> Boolean
): String
This function returns a character sequence which contains all the characters, except first characters which satisfy the given predicate.
CharSequence.elementAt(index: Int): Char This function returns the character at the given index or IndexOutOfBoundsException in case the index number is bigger than the size of the char sequence.
CharSequence.indexOf(char: Char, startIndex: Int = 0,
ignoreCase: Boolean = false
): Int
This function returns the index of the given character’s first occurrence.
CharSequence.indexOfFirst(
predicate: (Char) -> Boolean
): Int
This function returns the index of the given character’s first occurrence.
CharSequence.indexOfLast(
predicate: (Char) -> Boolean
): Int
This function returns the index of the given character’s last occurrence.
CharSequence.getOrElse(index: Int, defaultValue: (Int) ->Char): Char This function returns the character at the given index in the char sequence or the default value if the index is bigger than the size of the char sequence.
CharSequence.getOrNull(index: Int): Char? This function returns the character at the given index in the char sequence or a null value if the index is bigger than the size of the char sequence.
Spread the love
Scroll to Top