What is the simplest way to split a string into a list of characters?

1.3k Views Asked by At

This appears to be covered by the Str module in the api documentation but according to this issue opened this is an oversight.

1

There are 1 best solutions below

0
On BEST ANSWER

This is perhaps the simplest, though certainly not the most efficient:

let split = s =>
    s |> Js.String.split("")
      |> Array.to_list
      |> List.map(s => s.[0])

This is more efficient, and cross-platform:

let split = s => {
    let rec aux = (acc, i) =>
        if (i >= 0) {
          aux([s.[i], ...acc], i - 1)
        } else {
          acc
        }

    aux([], String.length(s) - 1)
}

I don't think it usually makes much sense to convert a string to a list though, since the conversion will have significant overhead regardless of method and it'd be better to just iterate the string directly. If it does make sense it's probably when the strings are small enough that the difference between the first and second method matters little.