Scala: divide strings
The title sounds a bit crazy but having the * function for java.lang.String in Scala ("a" * 3 = "aaa"
), why don't we have a / function so that "aaa" / "a" = 3
?
Cheers
Parsa开发者_StackOverflowI like the thinking. I'll answer with a question: why isn't there - function when we have a + function?
implicit def strDivider(s:String) = new {
def /(q:String): Int = s.grouped(q.length).takeWhile(_ == q).size
}
scala> "aaa" / "a"
res0: Int = 3
scala> "abc" / "x"
res1: Int = 0
scala> "aaa" / "aa"
res2: Int = 1
Such an operation seems a bit odd. What would it mean to divide "abc" / "x"
? The String.split()
function seems more general purpose and useful here.
You could also divide String
s by Int
s:
def divide(s: String, i: Int): (String,String) = {
require(i>0)
val Pattern = ("(.+)" + """\1""" * i + "(.*)").r
val Pattern(q, r) = s
(q,r)
}
assert(divide("aaa", 3) == ("a", ""))
assert(divide("aaaa", 3) == ("a", "a"))
assert(divide("abababc", 3) == ("ab", "c"))
assert(divide("abc", 1) == ("abc", ""))
assert(divide("foobar", 3) == ("", "foobar"))
a construct like "a" * 3
is used for things like creating separators when printing output to stdout so you can do "-" * 72
instead of typing 72 hyphens on a line. I don't see what benefit you could get from dividing though.
精彩评论