tags:

views:

132

answers:

4

Hi folks,

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

+2  A: 

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.

Greg Hewgill
A: 

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.

bemace
+5  A: 

I 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
huynhjl
Thanks for the answer. Neither one makes sense. I got interested in that while thinking of a stupid way of removing extra whitespace from a document.
parsa28
+1  A: 

You could also divide Strings by Ints:

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"))
mkneissl