Is it possible if given a string I could get each character composing that string?
In Haskell, strings are just (linked) lists of characters; you can find the line
type String = [Char]
somewhere in the source of every Haskell implementation. That makes tasks such as finding the first occurence of a certain character (elemIndex 'a' mystring
) or calculating the frequency of each character (map (head &&& length) . group . sort
) trivial.
Because of this, you can use the usual syntax for lists with strings, too. Actually, "foo"
is just sugar for ['f','o','o']
, which in turn is just sugar for 'f' : 'o' : 'o' : []
. You can pattern match, map and fold on them as you like. For instance, if you want to get the element at position n
of mystring
, you could use mystring !! n
, provided that 0 <= n < length mystring
.
Well, the question does say he wants an array:
import Data.Array
stringToArray :: String -> Array
stringToArray s = listArray (0, length s - 1) s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With