rosy
rosy

Reputation: 146

How to check the strings contains same characters in scala?

I want to check the strings contains same characters. for example My strings are :

BCE
CE

I want the result as,

BEC = BCE //true
ECB = BCE //true
CEB = BCE //true
CBE = BCE //true
EBC = BCE //true

CE = EC //true

Upvotes: 1

Views: 875

Answers (3)

elm
elm

Reputation: 20435

Consider this approach,

implicit class RichString(val s1: String) extends AnyVal {
  def sameAs(s2: String) = s1.sorted == s2.sorted
}

Use it like this, "CBE".sameAs("BCE") .

Upvotes: 4

Mihai Toader
Mihai Toader

Reputation: 12253

It seems, from your examples, that you only want to check if the string is a permutation of another string. A quick way of doing it is to just sort the chars and compare the result. A more efficient method is to build a histogram of one of the strings and then go through the other string and decrement the histogram count for each char as you find them in the second string. If at the end you have an empty histogram the strings are the same.

Upvotes: 1

Rex Kerr
Rex Kerr

Reputation: 167921

Strings can be implicitly converted to collections, and collections have a toSet method that make the contents a set, and set identity is independent of order.

Upvotes: 6

Related Questions