Splitting string into groups

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

    Edit: Have to read more carefully. Below is no functional code.

    Sometimes, a little mutable state helps:

    def group(s : String) = {
      var tmp = ""
      val b = Seq.newBuilder[String]
    
      s.foreach { c =>
        if ( tmp != "" && tmp.head != c ) {
          b += tmp
          tmp = ""
        }
    
        tmp += c
      }
      b += tmp
    
      b.result
    }
    

    Runtime O(n) (if segments have at most constant length) and tmp.+= probably creates the most overhead. Use a string builder instead for strict runtime in O(n).

    group("aaaabbcddeeeeeeffg")
    > Seq[String] = List(aaaa, bb, c, dd, eeeeee, ff, g)
    

提交回复
热议问题