Splitting string into groups

后端 未结 9 973
再見小時候
再見小時候 2020-12-15 09:52

I\'m trying to \'group\' a string into segments, I guess this example would explain it more succintly

scala> val str: String = \"aaaabbcddeeeeeeffg\"
...          


        
9条回答
  •  既然无缘
    2020-12-15 10:48

    def group(s: String): List[String] = s match {
      case "" => Nil
      case s  => s.takeWhile(_==s.head) :: group(s.dropWhile(_==s.head))
    }
    

    Edit: Tail recursive version:

    def group(s: String, result: List[String] = Nil): List[String] = s match {
      case "" => result reverse
      case s  => group(s.dropWhile(_==s.head), s.takeWhile(_==s.head) :: result)
    }
    

    can be used just like the other because the second parameter has a default value and thus doesnt have to be supplied.

提交回复
热议问题