简体   繁体   English

如何在scala中比较两个字符串?

[英]How to compare two strings in scala?

I want to compare two strings in scala.我想在 Scala 中比较两个字符串。 for example,例如,

My Strings are:我的字符串是:

scala java
scala java c++
scala c++

I want to compare the string我想比较字符串

" scala c++ " with each strings scala c++ ”与每个字符串

Results should be,结果应该是,

scala c++ = scala java   // false
scala c++ = scala java c++  // false
scala c++ = scala c++   // true

In Scala you can use == for equality在 Scala 中,您可以使用==表示相等

scala> "scala c++" == "scala java"
res0: Boolean = false
scala> "scala c++" == "scala java c++"
res1: Boolean = false
scala> "scala c++" == "scala c++"
res2: Boolean = true

The == method is defined in the AnyRef class. == 方法在 AnyRef 类中定义。 Since the methods first checks for null values, and then calls the equals method on the first object to see if the two objects are equals you dont have to do a special null check;由于这些方法首先检查空值,然后在第一个对象上调用 equals 方法来查看两个对象是否相等,因此您不必进行特殊的空检查;

"test" == null
res0: Boolean = false

See the Scala getting started guide and strings请参阅Scala 入门指南字符串

From " An Overview of the Scala Programming Language Second Edition ";摘自《 Scala 编程语言概述第二版》;

"The equality operation == between values is designed to be transparent with respect to the type's representation. For value types, it is the natural (numeric or boolean) equality. For reference types, == is treated as an alias of the equals method from java.lang.Object . That method is originally defined as reference equality, but is meant to be overridden in subclasses to implement the natural notion of equality for these subclasses . For instance, the boxed versions of value types would implement an equals method which compares the boxed values. By contrast, in Java, == always means reference equality on reference types. While this is a bit more efficient to implement, it also introduces a serious coherence problem because boxed versions of equal values might no longer be equal with respect to ==. Some situations require reference equality instead of user-dened equality. An example is hash-consing, where eciency is paramount. For these cases, class AnyRef defines an additional eq me “值之间的相等操作==被设计为相对于类型的表示是透明的。对于值类型,它是自然的(数字或布尔)相等。对于引用类型, ==被视为equals方法的别名来自java.lang.Object 。该方法最初定义为引用相等,但旨在在子类中重写以实现这些子类的自然相等概念。例如,值类型的盒装版本将实现一个 equals 方法比较装箱的值。相比之下,在 Java 中,== 总是表示引用类型的引用相等。虽然这实现起来更有效,但它也引入了严重的一致性问题,因为相等值的装箱版本可能不再等于关于 ==。有些情况需要引用相等而不是用户定义的相等。一个例子是 hash-consing,其中效率是最重要的。对于这些情况,类AnyRef定义了一个额外的eq me thod, which cannot be overridden, and is implemented as reference equality (ie, it behaves like == in Java for reference types)." thod,它不能被覆盖,并且被实现为引用相等(即,它的行为类似于 Java 中的==引用类型)。”

要添加等式比较,您可以使用!=表示不等式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM