Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to list of char

Tags:

I want to write a function that taking a string and return a list of char. Here is a function, but I think it is not do what I want ( I want to take a string and return a list of characters).

let rec string_to_char_list s =     match s with       | "" -> []       | n -> string_to_char_list n 
like image 723
Quyen Avatar asked Apr 09 '12 03:04

Quyen


People also ask

How do I split a string into a list in Word?

To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.

How do you split a string into a list in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.


2 Answers

Aside, but very important:

Your code is obviously wrong because you have a recursive call for which all the parameters are the exact same one you got in. It is going to induce an infinite sequence of calls with the same values in, thus looping forever (a stack overflow won't happen in tail-rec position).


The code that does what you want would be:

let explode s =   let rec exp i l =     if i < 0 then l else exp (i - 1) (s.[i] :: l) in   exp (String.length s - 1) [] 

Source: http://caml.inria.fr/pub/old_caml_site/FAQ/FAQ_EXPERT-eng.html#strings


Alternatively, you can choose to use a library: batteries String.to_list or extlib String.explode

like image 168
Ptival Avatar answered Oct 07 '22 00:10

Ptival


Try this:

let explode s = List.init (String.length s) (String.get s) 
like image 26
smac89 Avatar answered Oct 06 '22 22:10

smac89