Splitting string into groups

后端 未结 9 991
再見小時候
再見小時候 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条回答
  •  猫巷女王i
    2020-12-15 10:30

    You could use some helper functions like this:

    val str = "aaaabbcffffddeeeeefff"
    
    def zame(chars:List[Char]) = chars.partition(_==chars.head)
    
    def q(chars:List[Char]):List[List[Char]] = chars match {
        case Nil => Nil
        case rest =>
            val (thesame,others) = zame(rest)
            thesame :: q(others)
    }
    
    q(str.toList) map (_.mkString)
    

    This should do the trick, right? No doubt it can be cleaned up into one-liners even further

提交回复
热议问题