Splitting string into groups

后端 未结 9 990
再見小時候
再見小時候 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:55

    You can split the string recursively with span:

    def s(x : String) : List[String] = if(x.size == 0) Nil else {
        val (l,r) = x.span(_ == x(0))
        l :: s(r) 
    }
    

    Tail recursive:

    @annotation.tailrec def s(x : String, y : List[String] = Nil) : List[String] = {
        if(x.size == 0) y.reverse 
        else {
            val (l,r) = x.span(_ == x(0))
            s(r, l :: y)
        }
    }
    

提交回复
热议问题