Reputation: 146
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
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
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
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