Scala學習之字符串篇(一):字符串的比較

在Scala中你只須要使用==就能夠判斷字符串相等,而不須要像Java同樣須要使用的equals方法來判斷。java

scala> val s1 = "hello"
s1: String = hello

scala> val s2 = "hello"
s2: String = hello

scala> val s3 = "h" + "ello"
s3: String = hello

scala> s1 == s2
res4: Boolean = true

scala> s1 == s3
res5: Boolean = true

使用==判斷字符串相等的好處是,能夠避免空指針異常。即==左邊的字符串是空,也能夠正常判斷。es6

scala> val s4 = null
s4: Null = null

scala> s4 == s3
res6: Boolean = false

scala> s3 == s4
res7: Boolean = false

忽略大小寫來比較兩個字符串是否一致,有兩個方法:一個是把兩個字符串都轉化爲大寫或者小寫再比較,另外一個是直接使用equalsIgnoreCase方法。ide

scala> val s1 = "hello"
s1: String = hello

scala> val s2 = "Hello"
s2: String = Hello

scala> s1.toUpperCase == s2.toUpperCase
res8: Boolean = true

scala> s1.equalsIgnoreCase(s2)
res9: Boolean = true

須要注意的是,使用以上兩個方法的時候,"."號左邊的字符串不能爲空。es5

scala> val s4: String = null
s4: String = null

scala> s4.equalsIgnoreCase(s2)
java.lang.NullPointerException
  ... 32 elided

scala> s4.toUpperCase == s2.toUpperCase
java.lang.NullPointerException
  ... 32 elided

Scala中的==定義在AnyRef類中,在Scala API文檔中的解釋爲。x == that:首先判斷x是否爲空,若是x爲空而後判斷that是否爲空,若是x不爲空那麼調用x.equals(that)來判斷是否相等。scala

相關文章
相關標籤/搜索