# 在 Scala 中比較字串

Suraj P 2023年1月30日 2022年6月15日 Scala Scala String

## 在 Scala 中使用 `equals()` 方法比較字串

``````string_one.equals(string_two)
``````

``````object MyClass {

def main(args: Array[String]) {

val one = "Tony"
val two = "Tony"
val ans = one.equals(two)
println(ans)

}
}
``````

``````true
``````

``````object MyClass {

def main(args: Array[String]) {

val one = "Tony"
val two = "toNy"
val ans = one.equalsIgnoreCase(two)
println(ans)

}
}
``````

``````true
``````

## 在 Scala 中使用 `==` 運算子比較字串

``````string_one == string_two
``````

`==` 方法檢查 `string_one``string_two` 的相等性。如果兩個字串相等，則返回 `true`；否則，它返回 `false`

``````object MyClass {

def main(args: Array[String]) {

val one = "tony"
val two = "tony"
if(one==two)
println(true)
else
println (false)

}
}
``````

``````true
``````

``````object MyClass {

def main(args: Array[String]) {

val one = "tony"

if(one == null)
println(true)
else
println (false)

}
}
``````

``````false
``````

``````object MyClass {

def main(args: Array[String]) {
val one = "tony"
val two = "TONY"
if(one == two)
println(true)
else
println (false)

}
}
``````

``````false
``````

``````object MyClass {

def main(args: Array[String]) {
val one = "tony"
val two = "TONY"
if(one.toLowerCase() == two.toLowerCase())
println(true)
else
println (false)

}
}
``````

``````true
``````

## Java 和 Scala 中的相等檢查

Java 和 Scala 在相等方面有不同的定義。Java 主要有兩種檢查相等的方法：一種是使用 `==` 運算子，它嚴格檢查 `reference` 相等，另一種是 `equals()` 方法，可以重寫以檢查物件。

Author: Suraj P

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.