Kotlin String Guide

The string is one of the most used data types in the programming world. String makes it easier to manipulate with an array of characters. A string is a sequence of characters such as “Hello world”. In kotlin, string is considered as basic data types but at runtime, it's not considered as primitive data type (such as int, byte, short etc).

Read Also : Kotlin Array Guide

Let's start by making a basic understanding of how to declare and define the string and continue with additional features provided by kotlin.

Kotlin String Guide


Syntax for Declaring a String

    val variableName : String = "String literal"

String initialization example:

fun main()
{
      val string : String = "Java Hungry"
      println(string)
}

Output
Java Hungry

Declaring the data type is not necessary. The above declaration can also be made in this way.

fun main()
{
    val string = "Java Hungry"
    println(string)
}

Output
Java Hungry

The above declaration creates an immutable string i.e once a literal is assigned to it another string literal cannot be assigned. Even in simpler words, an immutable String is not further modifiable.

Syntax for Creating a Mutable String

To create a modifiable or a mutable string variable, that can be reassigned, the syntax is:

fun main()
{
    var str = "Java Hungry"
    println(str)
    str = "Hello From " + str
    println(str)
}

Output
Java Hungry
Hello From Java Hungry

Accessing elements of String

A single character/elements in a String can be accessed through operator notation [] or get(index) method. Examples are below

fun main(){
   val str = "Alive is Awesome";
   println(str[0])      // A
   println(str[1])      // l
   println(str.get(2))  // i
}

Output
A
l
i

To access all elements in one go, one of the easier ways is using a for loop

fun main(){
    val str = "Javahungry";
    for (element in str){
        print("*"+ element + "*")
    }
 }

Output
*J*
*a*
*v*
*a*
*h*
*u*
*n*
*g*
*r*
*y*

Important functions/properties of String class

1. length

Returns the length of String. An example is given below

fun main()
{
    var str = "Be in Present"
    var result = str.length
    println(result)
}

Output
13

2. contains(queryString : String)

Returns true if the string contains queryString else return false. An example is given below

fun main()
{
    var str = "Alive is Awesome"
    var result = str.contains("Alive")
    println(result)
}

Output
true

3. plus(toConcatenate : Any)

Return string by concatenating it with toConcatenate value. toConcatenate can even be number or some other data type.

fun main()
{
    var str = "Hello"
    var str1 = str.plus(" from Java Hungry")
    println(str1)   // prints “Hello from Java Hungry”
    var str2 = str.plus(5)
    println(str2)   // prints “Hello5”
}

Output
Hello from Java Hungry
Hello5

4. subSequence(startIndex : Int, endIndex : Int)

Return the string containing elements from startIndex element upto endIndex element. Both startIndex and endIndex elements are inclusive in the output.

fun main()
{
    var str = "Alive is Awesome"
    var str1 =  str.subSequence(0,5);
    println(str1)   //Alive
    var str2 =  str.subSequence(6,8);
    println(str2)   //is
}

Output
Alive
is


5. toInt()

Returns the integer that is contained in string.

fun main()
{
    val numberStr : String = "5"
    var result = numberStr.toInt()    
    println(result)
}

Output
5

Kotlin String contains function for other data types too i.e toByte(), toBigDecimal(), toBoolean(), toBigInteger(), toByte(), toDouble(), toCollection(), toFloat(), toHashSet() etc.

Be careful, if the string contains letters other than the desired number or value, the function will throw java.lang.NumberFormatException.

To avoid this exception, there are functions available that will return null if the string does not contain the desired number.

These functions are toByteOrNull(), toBigDecimalOrNull(), toBooleanOrNull(), toBigIntegerOrNull(), toByteOrNull(), toDoubleOrNull(), toCollectionOrNull(), toFloatOrNull(), toHashSetOrNull() etc

String Templates

One of the best features of kotlin string which is not present in a lot of high-level programming languages is templates. String templates are literals that contain expressions. It means that a string can be evaluated as any other expression. For example:

fun main()
{
 val numberOne = 1;
 val numberTwo = 2;
 println("$numberOne + $numberTwo = ${numberOne + numberTwo}")

}

Output
1 + 2 = 3

Did you notice how easy it becomes to manipulate with strings using kotlin string templates? Now let's try to digest the syntax.

The dollar sign $ is used to include a variable/constant value.
The curly brackets {} are used to include a kotlin expression.

In the above example, we used dollar sign with numberOne and numberTwo to include their values in the string and used $ with curly brackets outside the numberOne + numberTwo expression to include its the result of an expression.

The string templates are very powerful and it can be used with conditional.

fun main()
{
    var temp = 35
    println("Today's temperature is $temp. ${if(temp > 30) "It is sunny out" else "It is cold out"}")

    temp = 20;
    println("Today's temperature is $temp. ${if(temp > 30) "It is sunny out" else "It is cold out"}")

}

Output:
Today's temperature is 35. It is sunny out
Today's temperature is 20. It is cold out

String Equality

We often need to compare two strings in programming. In kotlin, there are many ways to compare string that it may confuse the programmer. But, worry not, just follow the tutorial. There are two types of equality check available in kotlin :

1. Structural Equality
2. Referential Equality

1. Structural Equality ("==")

The "==" (double equal) checks the equality of the content/data in the variable or objects. For most of the built-in data types including string equals functions and "==" operators are same i.e "==" operator invokes equals function.

The reverse of == in kotlin is  != which is used to compare if both the values are not equal to each other.

2. Referential equality (‘===’)

The "===" (triple equal) is used to compare reference (location in memory) of two objects or variables.  In Java, "==" checks the reference of the object, but in kotlin, it is reverse. The reverse of "===" in kotlin is "!==" which checks if both the variable/objects are not pointing to the same object.

fun main(){

    val str1 : String = "string1"

    val str2 : String = "string2"

    val str3 : String = "string1"

    // Structural Equality

    println(str1.equals(str2)) // false

    println(str1.equals(str3)) // true

    println(str1 == str2) // false

    println(str1 == str3) // true

    println(str1 != str2) // true

    // Referential equality

    println(str1 === str2); // false

}

Output
false
true 
false 
true 
true 
false 

Escape Sequence


An escape character is a character that starts with \ which results in an alternative interpretation of some characters in a character sequence (string). Like many other high-level programming languages, kotlin strings use escape characters to store punctuation marks like quotations or special characters like \n for new-line and \$ for dollar sign because quotations are used to represent starting and ending of a string and $ sign is used for string templates.

Some of the most commonly used escape characters in kotlin:
  • \" : double quote
  • \" : single quote
  • \n :newline
  • \\ : backslash 
  • \b :backspace
  • \t : tab

To keep updated with the new tutorials and guidelines regarding kotlin, stay tuned to our blog. If you have any further queries regarding kotlin String, do let me know in the comments section.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry