Slice/Group a sequence of equal chars in F#

前端 未结 6 1802
难免孤独
难免孤独 2020-12-21 15:34

I need to extract the sequence of equal chars in a text.

For example: The string \"aaaBbbcccccccDaBBBzcc11211\" should be converted to a list of strings

6条回答
  •  天命终不由人
    2020-12-21 15:46

    How about with groupby

    "aaaBbbcccccccD"
    |> Seq.groupBy id
    |> Seq.map (snd >> Seq.toArray)
    |> Seq.map (fun t -> new string (t))
    

    If you input order matters, here is a method that works

    "aaaBbbcccccccDaBBBzcc11211"
    |> Seq.pairwise
    |> Seq.toArray
    |> Array.rev
    |> Array.fold (fun (accum::tail) (ca,cb) -> if ca=cb then System.String.Concat(accum,string ca)::tail else string(ca)::accum::tail)   (""::[])
    

提交回复
热议问题