Android Developer
Android Developer

Reputation: 9643

Using in operator to compare string with range of strings

I am using in operator to check whether a value is in range. But I am not able to understand exactly how the comparison with range of strings is done. Below are the few arguments and their output which I have tried:

   println("KOTLIN" in "J".."K")
false

   println("KOTLIN" in "Java".."Scala")
true

    println("KOTLIN" in "Java".."Bhuv")
false

Upvotes: 1

Views: 2897

Answers (3)

susheel balan
susheel balan

Reputation: 1

Lexicographic Order aka Dictionary Order, e.g.. when scrolling down the words in a dictionary, the order of the words will be

1.Java
2.Kotlin
3.Scala

Hence,

(Kotlin in Java..Scala) will return true.

In normal english, the code above is stating that by using the Dictionary Order, the word Kotlin is found in between the word Java and Scala.

Upvotes: 0

Raman
Raman

Reputation: 19585

Based on your question, I think you are confused about this result:

println("KOTLIN" in "J".."K") is false

Basically, if you were to sort these using Java's String comparison implementation, you would see this:

Bhuv
J
Java
K
KOTLIN
KZ

Since K is lexicographically before KOTLIN, the result you are seeing makes total sense.

Upvotes: 3

s1m0nw1
s1m0nw1

Reputation: 81879

in is compiled down to the following function (defined in kotlin.ranges.Range.kt):

public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive

So "KOTLIN" in "J".."K" results in:

("J".."K").contains("KOTLIN")

The comparison in this case relies on normal String comparisons since >= and <= are compiled down to variations of compareTo. The implementation looks as follows:

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

So, "KOTLIN" in "Java".."Scala" is equal to the following:

"KOTLIN".compareTo("Java") >=0 && "KOTLIN".compareTo("Scala") <= 0

Upvotes: 7

Related Questions