Scala: Finding the difference, intersection, and distinct characters in a String

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 1.11, “String Differences, Intersections, and Distinct Characters.”


In Scala, you need to perform advanced string operations, such as finding the difference between two strings, the common characters between two strings, or the unique characters in a string.


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"

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"


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.

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

See Also