English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to compare strings

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to compare two strings in Kotlin.

Example1: Comparing two strings

fun main(args: Array<String>) {
    val style = "Bold"
    val style2 = "Bold"
    if (style == style2)
        println("Equal")
    else
        println("Not equal")

When the program is run, the output is:

Equal

In the above program, we have two strings style and style2. We only use the equality operator (==) to compare two strings, which will have the valueBoldAndBoldComparison and output Equal.

Example2: Using equals() to compare two strings

fun main(args: Array<String>) {
    val style = "Bold"
    val style2 = "Bold"
    if (style.equals(style2))
        println("Equal")
    else
        println("Not equal")
}

When the program is run, the output is:

Equal

In the above program, we have two strings, style and style2They all contain the same words Bold.

As you can see, we have already used the equals() method to compare strings. Like the example1It will also have the same valueBoldAndBoldComparison.

Example3: Using === to compare two strings (does not work)

fun main(args: Array<String>) {
    val style = buildString { "Bold" }
    val style2 = buildString { "Bold" }
    if (style === style2)
        println("Equal")
    else
        println("Not equal")
}

When the program is run, the output is:

Not equal

In the above program, we did not create a string using quotes, but instead used the auxiliary method buildString to create a String object.

In addition to using the == operator to compare strings, we also use === (reference equality operator) to compare strings. This operator compares style and style2Whether they are essentially the same object.

Because they are notNot equalPrinted on the screen.

Example4: Different methods to compare two strings

This is a string comparison that may be performed in Java.

fun main(args: Array<String>) {
    val style = buildString { "Bold" }
    val style2 = buildString { "Bold" }
    var result = style.equals("Bold") // true
    println(result)
    result = style2 === "Bold" // false
    println(result)
    result = style === style2 // false
    println(result)
    result = "Bold" === "Bold" // true
    println(result)
}

When the program is run, the output is:

true
false
false
true

The following is the equivalent Java code:Java Program to Compare Strings.

Comprehensive Collection of Kotlin Examples