Scala String differences, intersections, and distinct characters

Scala String problem: You need to find the difference between two strings, the common characters between two strings, or the unique characters in a string.

Solution

You can perform all of these operations with built-in methods. Use the diff method to find the differences between two strings:

val a = "Four score and six years ago"
val b = "Four score and seven years ago"
a diff b   // "ix"
b diff a   // "vene"

(Notice that the value returned by the diff method depends on the order in which it’s called.)

Use the intersect method to find the characters that are common between two strings:

val a = "Alvin"
val b = "Alexander"
a intersect b   // yields "Aln"
b intersect a   // yields "Aln"

Use the distinct method to find the distinct/unique characters in a String:

"hello world".distinct            // yields "helo wrd"
"hannah".distinct                 // yields "han"
"Four score and seven".distinct   // yields "Four sceandv"

Discussion

Scala is known for having extensive library support, as you can see from these built-in methods. Remember to review the methods that are available on a String; if the behavior you need seems common, it’s probably already there.

See Also

  • You can find more information about these methods in the Scaladoc of the StringOps class: http://www.scala-lang.org/api/current/scala/collection/immutable/StringOps.html