How to slice a string into substrings of a given length

I have a string that I want to slice into an array of substrings of a given length n. I'm not interested in the remainder (if the length of the string cannot be split by n without a remainder)

let ChopString (myString : string) n = 
    let res = 
        seq{ 
            for i = 0 to myString.Length / n - 1 do
                yield( String.sub myString (i*n) n )
            }    
        |> Seq.to_array
    res

      

This is the best I could do. It seems ugly to me.

Is there a nicer / shorter version of this, perhaps without a loop?

+1


source to share


2 answers


stringInstance.[start..end]

much more readable than String.sub

. This is what I came up with:


let chop (input : string) len = 
    seq { for start in 0 .. len .. input.Length / len
        do yield input.[start..start + len - 1] }
    |> Seq.to_array

      



Or you can use:


let chop (input : string) len = 
    Array.init (input.Length / len) (fun index ->
        let start = index * len
        input.[start..start + len - 1])

      

+8


source


Craig Stuntz left an answer here that is currently missing. Anyway, he pointed to an article on F # which has two functions for manipulating strings: explode

and implode

. These two functions belong to the ML standard library. Here's the code:

let rec explode str = 
       let len = String.length str in
           if len=0 then [] else 
              (String.sub str 0 1) :: explode (String.sub str 1 (len-1)) 

let rec implode lst = match lst with
                         []  -> ""
                       | x1 :: x2 -> x1 ^ implode x2

      



explode

breaks a line into a list of lines, where each line is one character.
implode

does the opposite - concatenates a list of strings into one string.
Both functions are recursive, so it would be interesting to compare performance.

0


source







All Articles