Kotlin String Example

In this Kotlin tutorial, we will learn important String methods or operations in Kotlin with examples.

In Kotlin, Strings are a sequence of characters. For example, "Hello World!" is a string literal.

In Kotlin, all strings are objects of the String class. Meaning, string literals such as "Hello world!" are implemented as instances of this class.

Example 1: Simple Kotlin String Example

The below Kotlin program creates a string, uses a string concatenation operation, and determines the width of the string.
package net.javaguides.kotlin.examples

fun main(args: Array<String>) {
 
    val s = "Source Code Examples"

    println(s)

    println("sourcecodeexamples" + ".net")

    println("The string has " + s.length + " characters")
}
Output:
Source Code Examples
sourcecodeexamples .net
The string has 20 characters

A string literal is created and passed to the s variable. The string is printed to the console with the println() method.

val s = "Source Code Examples"

println(s)

In Kotlin, strings are concatenated with the + operator:

println("sourcecodeexamples" + ".net")

Example 2: Get the First and Last Characters of a String 

The below example shows how to get the first and last characters of a string. It uses indexing operations and alternative string methods.
package net.javaguides.kotlin.examples

fun main(args: Array<String>) {

    val s = "sourcecodeexamples.net"

    println(s[0])
    println(s[s.length-1])

    println(s.first())
    println(s.last())
}
Output:
s
t
s
t
The indexes start from zero; therefore, the first character has a zero index. The index of the character is placed between square brackets.
println(s[0])
println(s[s.length-1])
The first() method returns the first character and the last() returns the last character of the string:
println(s.first())
println(s.last())

Example 3: Kotlin Comparing Strings

This Kotlin example shows how to compare two strings using the == operator and the compareTo() method to compare string content.
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val s1 = "SourceCodeExamples"
    val s2 = "sourcecodeexamples"

    if (s1 == s2) {

        println("Strings are equal")
    } else {

        println("Strings are not equal")
    }

    println("Ignoring case")

    val res = s1.compareTo(s2, true)

    if (res == 0) {

        println("Strings are equal")
    } else {

        println("Strings are not equal")
    }
}
Output:
Strings are not equal
Ignoring case
Strings are equal

The == operator compares structural equality, that is, the content of the two strings:
if (s1 == s2) {
The compareTo() method compares two strings lexicographically, optionally ignoring the case:
val res = s1.compareTo(s2, true)

Example 4: Kotlin String Looping 

The example loops over a string using a for loop, forEach loop, and forEachIndexed loop.
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val phrase = "Source Code Examples"

    for (e in phrase) {

        print("$e ")
    }

    println()

    phrase.forEach {
        e - > print(String.format("%#x ", e.toByte()))
    }

    println()

    phrase.forEachIndexed {
        idx,
        e - > println("phrase[$idx]=$e ")
    }
}
Output:
S o u r c e   C o d e   E x a m p l e s 
0x53 0x6f 0x75 0x72 0x63 0x65 0x20 0x43 0x6f 0x64 0x65 0x20 0x45 0x78 0x61 0x6d 0x70 0x6c 0x65 0x73 
phrase[0]=S 
phrase[1]=o 
phrase[2]=u 
phrase[3]=r 
phrase[4]=c 
phrase[5]=e 
phrase[6]=  
phrase[7]=C 
phrase[8]=o 
phrase[9]=d 
phrase[10]=e 
phrase[11]=  
phrase[12]=E 
phrase[13]=x 
phrase[14]=a 
phrase[15]=m 
phrase[16]=p 
phrase[17]=l 
phrase[18]=e 
phrase[19]=s 
From the above program, we traverse the string with a for loop and print each of the characters:
for (e in phrase) {
    print("$e ")
}
We traverse over a loop with a forEach loop and print a byte value of each of the characters:
phrase.forEach { e -> print(String.format("%#x ", e.toByte())) }
With forEachIndexed, we print the character with its index:
phrase.forEachIndexed { idx, e -> println("phrase[$idx]=$e ")  }

Kotlin has methods for working with the case of string characters.

Example 5: Kotlin String Case

Let's write the Kotlin program to demonstrate the usage of below four operations:
  • capitalize()
  • toUpperCase()
  •  toLowerCase()
  • decapitalize()
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val s = "source code examples"

    println(s.capitalize())
    println(s.toUpperCase())
    println(s.toLowerCase())

    println("my website ".decapitalize())
}
Output:
Source code examples
SOURCE CODE EXAMPLES
source code examples
my website 

Example 6: Remove Leading and Trailing Whitespaces

In this Kotlin example, we use trim(), trimEnd(), and trimStart() methods to remove leading and trailing whitespaces.
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val s = " Source Code Examples.Net     "

    println("s has ${s.length} characters")

    val s1 = s.trimEnd()
    println("s1 has ${s1.length} characters")
    println("s1 -> " + s1)

    val s2 = s.trimStart()
    println("s2 has ${s2.length} characters")
    println("s2 -> " + s2)

    println(s.trim())
    val s3 = s.trim()
    println("s2 has ${s3.length} characters")
    println("s3 ->  ${s3}")
}
Output:
s has 30 characters
s1 has 25 characters
s1 ->  Source Code Examples.Net
s2 has 29 characters
s2 -> Source Code Examples.Net     
Source Code Examples.Net
s2 has 24 characters
s3 ->  Source Code Examples.Net
The trimEnd() method removes trailing white spaces:
val s1 = s.trimEnd()
The trimStart() method removes leading white spaces:
val s2 = s.trimStart()
The trim() method removes both trailing and leading white spaces:
val s3 = s.trim()

Example 7: Kotlin String Interpolation

String interpolation is a variable substitution with its value inside a string. In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression.
Kotlin string formatting is more powerful than basic interpolation.
The below example demonstrates how to do string interpolation in Kotlin:
package net.javaguides.kotlin.examples

fun main(args: Array<String>) {

    val name = "Ramesh"
    val age = 29

    println("$name is $age years old")

    val msg = "Today is a sunny day"

    println("The string has ${msg.length} characters")
}
Output:
Ramesh is 29 years old
The string has 20 characters
The two variables are interpolated within the string; i.e. they are substituted with their values:
println("$name is $age years old")
Here we get the length of the string. Since it is an expression, we need to put it inside the {} brackets:

println("The string has ${msg.length} characters")

Example 8: Kotlin Empty/Blank String 

Kotlin distinguishes between empty and blank strings. An empty string does not have any characters, a blank string contains any number of white spaces.

Let's write the Kotlin program to demonstrate the below two String operations:
  • isEmpty()
  • isBlank()
The example tests if a string is blank or empty:
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val s = "\t"

    if (s.isEmpty()) {

        println("The string is empty")
    } else {

        println("The string is not empty")
    }

    if (s.isBlank()) {

        println("The string is blank")
    } else {

        println("The string is not blank")
    }
}
Output:
The string is not empty
The string is blank
The isEmpty() returns true if the string is empty:
if (s.isEmpty()) {
The isBlank() returns true if the string is blank:
if (s.isBlank()) {


Comments