Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Strings in Scala using > and <

Tags:

string

scala

I'm trying to compare two Strings in Scala, trying to find out which comes first in the alphabet. I.e. a before b, aab before abb, etc.

It seems like the > and < operators are doing exactly this job:

scala> "b" > "a"

res14: Boolean = true

scala> "b" < "a"

res15: Boolean = false

scala> "aab" < "abb"

res16: Boolean = true

However, the (that:A):Boolean" rel="nofollow noreferrer">doc did not enlighten me on what this really does, and none of the tutorials online seem to be using this method to compare strings. Thus, I was wondering:

  • Is this a fail safe approach to do what I want to do, i.e. compare two Strings for alphabetical order?

  • Is there a more common approach in Scala that I am missing here?

  • How exactly does it work - e.g.

scala> "?" > "!" res25: Boolean = true

is not intuitive to me.

like image 975
patrick Avatar asked May 07 '26 22:05

patrick


1 Answers

As you saw in the docs, you can use the defined > (and all the others) for Strings. Ultimately, this breaks down the elements of the String into the underlying Chars and they are unicode. So you need to compare the unicode values for them to emulate the logic exhibited by the scalac.

Referring to a definitive list one finds that

U+0021 ! ! Exclamation mark

and

U+003F ? ? Question mark

so, indeed, !<? is true.

I believe that the comparison action is failsafe for any unicode sequence that you can supply. See even:

val string1 = "\u2200"
val string2 = "\uFB30"

string1 < string2

val string3 = string1 + string2
val string4 = string2 + string1

string3 < string4
string4 < string3

string3 == string1 + string2
string4 == string1 + string2

which in my worksheet gives me:

string1: String = ∀
string2: String = אּ // note: aleph comes after All in the unicode definition.

res7: Boolean = true

string3: String = ∀אּ
string4: String = אּ∀

res8: Boolean = true
res9: Boolean = false

res10: Boolean = true
res11: Boolean = false
like image 166
Shawn Mehan Avatar answered May 10 '26 14:05

Shawn Mehan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!