Strings in Kotlin

You are here:
Estimated reading time: 6 min

In this tutorial, we will be learning how to work with Strings in Kotlin.

We will also be discussing the following topics:

  • String Literals
  • Strings Templates/Interpolation
  • String Comparison using compareTo, equals and equality operator
  • String Properties
  • String methods such as replace, trim, contains, etc.

A string is a sequence of characters. Strings in Kotlin are created by using double quotes (“xxxxxxx”)

In Kotlin, strings are represented as objects of the String class i.e. all string literals, such as “Hello”, “abc$123”, etc. are considered instances/objects of the String class.

Declaration:

fun main(){
    var str1: String = "Hello"
    //OR
    var str2 = "World"
}

You can also declare an empty string in Kotlin:

fun main(){
    var emptyStringExample = String()
}

Strings in Kotlin are immutable i.e. once declared, they can not be changed or modified. All modification operations create a new string, rather than modifying a string in-place.

fun main(){
    var tempString = "Bruce Wayne"
    var tempString += "is Batman"
}

In the above example, the string “is Batman” will not be added to the existing string “Bruce Wayne”. Instead, a new string “Bruce Wayne is Batman” will be created and the reference of the tempString variable will be changed so that it refers/points to this new string.

String Properties in Kotlin

Length Property

fun main(){
    var strongestAvenger = "The Hulk"
    println(strongestAvenger)
    println(strongestAvenger.length)
}

The length property of strings is used to get the number of characters in a string. Here, the number of characters in the string “The Hulk” is calculated to 8. The space is also counted as a character in the string.

String Concatenation in Kotlin

Strings in Kotlin can be joined together using the + operator.

fun main(){
    var word1 = "Wubba"
    var word2 = "Lubba"
    var word3 = "Dub"
    println(word1+word2+word3+word3)
}

Here, the expression word1+word2+word3+word3 equates to “Wubba”+”Lubba”+”Dub”+”Dub”. Therefore, the output is “WubbaLubbaDubDub”.

To add spaces between the words, the following can be executed, instead:

fun main(){
    var word1 = "Wubba"
    var word2 = "Lubba"
    var word3 = "Dub"
    println(word1+" "+word2+" "+word3+" "+word3)
}

Here, the output will be “Wubba Lubba Dub Dub”.

Indexing in Kotlin Strings

Characters in a String can easily be accessed using indices, where the indices start from 0 and go up to n-1, where n is the no. of characters in a string.

A character at index i can simply be accessed by writing the name of the string variable followed by the index enclosed within square brackets, as shown below:

fun main(){
    var Amazon = "Wonder Woman"
    println(Amazon[0])
    println(Amazon[6])
    println(Amazon[8])
}

In the above example, Amazon[0] will print “W” i.e. the first character of the string.

Amazon[6] will print “ “ i.e a space, as the character at index 6 is a spacebar.

Amazon[8] will print “o”.

The first and last characters of the string can also be printed using the first() and last() Library functions.

fun main(){
    var Amazon = "Wonder Woman"
    println(Amazon.first())
    println(Amazon.last())
}

The first() method returns the first character of the string and the last() method returns the last character of the string.

Comparing Strings in Kotlin

using equality operator (==)

Strings can be compared using the equality operator (==). The operator compares the strings structurally i.e. it compares the contents of the strings and returns true if they are equal, else returns false.

fun main(){
    var word1 = "kotlintutorials.com"
    var word2 = "kotlintutorials.com"
    var word3 = "kotlin"
    print(word1==word2) //true
    print(word1==word3) //false
}

using compareTo() method

The compareTo() method compares the strings lexicographically i.e. it compares the characters on the basis of their ASCII values and returns the difference between their ASCII values as a result of the comparison.

The difference between the ASCII values of the first non-matching characters in the strings is returned as the result.

If this difference is 0, both objects are equal.

If this difference is a negative number, object1<object2.

If this difference is a positive number, object2>object1.

Refer to this chart for ASCII values:

fun main(){
    var word1 = "hey"
    var word2 = "hey"
    var word3 = "hello"
    var word4 = "hi"
    var word5 = "HEY"
    println(word1.compareTo(word2)) //Output --> 0
    println(word1.compareTo(word3)) //Output --> 13
    println(word1.compareTo(word4)) //Output --> -4
    println(word1.compareTo(word5)) //Output --> 32
}

Here, word1.comparedTo(word2) returns 0 as both “hey” and “hey” are equal.

Word1.compareTo(word3) returns 13. As mentioned above, the difference between the ASCII values of the first non-matching characters in the strings is returned as the result. In the comparison between “hey” and “hello”, the first non-matching characters are “y” and “l”. Their ASCII values are 121 and 108 respectively. Therefore, the result is 121-108 = 13.

Word1.compareTo(word4) returns the difference between the ASCII values of “e” and “i” i.e. 101 and 105 respectively. Therefore, the output is 101-105 = -4.

Word1.compareTo(word4) returns the difference between the ASCII values of “h” and “H” i.e. 101 and 105 respectively. Therefore, the output is 104-72 = 32.

using equals() method

In the case of strings, the equals() method works similarly as the equality operator (==). It returns true if the strings being compared are equal, else false is returned.

fun main(){
    var word1 = "hey"
    var word2 = "hey"
    var word3 = "hello"
    println(word1.equals(word2)) //Output --> true
    println(word1.equals(word3)) //Output --> false
}

String Templates in Kotlin/String Interpolation in Kotlin

String interpolation is also known as variable substitution.

In Kotlin, we use ‘$’ to interpolate variables in strings and ‘${expression}’ to interpolate an expression inside a string.

fun main(){
    var length = 5
    var width = 10
    print("The length is $length and width is $width.")
    print("The area is ${length*width}.")
}

Here, in the first print statement, the $length is substituted by the value of the variable-length i.e. 5. Similarly, the $width is substituted by the value of the variable width i.e. 10.

In the second print statement, the expression ${length*width} is substituted by the values of variables length and width i.e. the expression is evaluated to 5*10 = 50.

String Escape Characters in Kotlin

Escape characters are special characters/set of characters in Kotlin that, when encountered by a compiler in a string, perform some special operation.

\n – New Line

\t – Tab Space

\ – used to put quotes (“) within a string i.e. as part of a string.

Example:

fun main(){
    print("Hello.\nThis is Kotlin.\n")
    print("\tPluto is not a planet anymore.\n")
    print("He said,\"With great power comes great responsibility.\"")
}

Output:

Manipulating letter case in Kotlin Strings

We can easily manipulate and change the letter case in Kotlin Strings using the following methods:

toUpperCase() – changes all letters of a string to upper case.

toLowerCase() – changes all letters of a string to lower case.

capitalize() – changes only the first letter of a string to upper case.

decapitalize() – changes only the first letter of a string to lower case.

Example:

fun main(){
    var hero="Captain America"
    println(hero.toUpperCase())
    println(hero.toLowerCase())
    
    var hero2="iron man"
    println(hero2.capitalize())
    
    var hero3="The Hulk"
    print(hero3.decapitalize())
}

Output:

Blank Strings v/s Empty Strings in Kotlin

In Kotlin, Empty Strings are strings without any characters.

Whereas, Blank Strings are strings that contain any number of whitespaces only.

All Empty strings are Blank Strings but vice versa is not true.

isEmpty() – This method is used to check whether a given string is empty or not. If a String is Empty, it returns True. Otherwise, it returns False.

IsBlank() – This method is used to check for Blank Strings. If a String is Blank, it returns True. Otherwise, it returns False.

Example:

fun main(){
    var str1=""
    if(str1.isEmpty())
        println("str1 is empty")
    else
        println("str1 is not empty")
    if(str1.isBlank())
        println("str1 is Blank")
    else
        println("str1 is not Blank")
    
    var str2=" "
    if(str2.isEmpty())
        println("str2 is empty")
    else
        println("str2 is not empty")
    if(str2.isBlank())
        println("str2 is Blank")
    else
        println("str2 is not Blank")
        
    var str3="\t"
    if(str3.isEmpty())
        println("str3 is empty")
    else
        println("str3 is not empty")
    if(str3.isBlank())
        println("str3 is Blank")
    else
        println("str3 is not Blank")
}

Output:

White Space Stripping in Kotlin Strings

Kotlin provides us the following methods to strip/remove whitespace from a string.

trim() – to remove whitespace from the beginning as well as the end of a string

trimStart() – to remove whitespace from the beginning of a string

trimEnd() – to remove whitespace from the end of a string

There is no method to remove whitespaces from the middle of a string.

Example:

fun main(){
    var str1="   Hello World!   "
    print(str1.trim())
    println("Kotlin")
    print(str1.trimStart())
    println("Kotlin")
    print(str1.trimEnd())
    println("Kotlin")
}

Output:

Kotlin startsWith() and endsWith() Methods

The startsWith() method is used to check whether a string starts with a specified character/set of characters.

It is used to check if a string starts with a given prefix.

The endsWith() method is used to check whether a string ends with a specified character/set of characters.

It is used to check if a string ends with a given suffix.

The startsWith() and endsWith() methods are case sensitive i.e. if the statement s1.startsWith(“Hello”) yields true, then the statement s1.startsWith(“hello”) will not yield True.

Both methods take the prefix/suffix as an argument in the method call.

Example:

fun main(){
    var str1="Peter Parker is Spiderman"
    if(str1.startsWith("Pet"))
        println("Starts with Pet")
    else
        println("Does not start with Pet")
        
    if(str1.startsWith("pet"))
        println("Starts with pet")
    else
        println("Does not start with pet")
    
    if(str1.endsWith("man"))
        println("Ends with man")
    else
        println("Does not end with man")
    
    if(str1.endsWith("Man"))
        println("Ends with Man")
    else
        println("Does not end with Man")   
}

Output:

Kotlin replace() Method

The replace() method takes 2 arguments as function parameters, the new sub-string and the older sub-string that is to be replaced with the new string.

exampleStr.replace(“newSubString”,”oldSubString”)

The method does not change the string in-place. Rather, it returns a new string with the changes.

Example:

fun main(){
    var str1="Thor is the Strongest Avenger"
    println(str1.replace("Thor","The Hulk"))
    //replace() does NOT change the string in place i.e. it does not cause any change in the string str1
    println(str1)
 }

Output:

Raw Strings in Kotlin/MultiLine Strings

Raw Strings in Kotlin can be declared by using triple quotes. They can contain newlines and any other characters.

Raw Strings do not identify any escape characters or sequences.

Example:

fun main(){
    var str1="""
    Captain America
    \n
    Black Panther
    """
    print(str1)
 }

Output:

Check if a String exists within another String in Kotlin

Kotlin provides us with the contains() method to check whether a given string exists in another string as a sub-string.

Example:

fun main(){
    var str1="The Incredible Hulk"
    if(str1.contains("Hulk"))
        print("WOAH")
    else
     print("BOO")
 }

In the above example, the output will we “WOAH”.

Other articles:

Kotlin v/s Java

Arrays in Kotlin

Functions in Kotlin

Extensions in Kotlin

For loops in Kotlin

References:

https://kotlinlang.org/docs/reference/functions.html

Was this article helpful?
Dislike 0
Views: 8