It seems as if there is no function in the standard library of type char -> string -> string
, which insert a char
in front of (or at the end of) a string
. There are workarounds, e.g. by using String.make
or String.blit
. Is there an elegant way to do this?
Use the strncat() function to append the character ch at the end of str.
The (^) operator concatenates two strings, e.g., # "hello" ^ ", " ^ "world!";; - : string = "hello, world!"
There is a way to match strings as a list of characters, using a function from SML (which you can write in OCaml) called 'explode' and 'implode' which --respectively -- take a string to a char list and vice versa.
uppercase_ascii s is s with all lowercase letters translated to uppercase, using the US-ASCII character set. lowercase_ascii s is s with all uppercase letters translated to lowercase, using the US-ASCII character set.
The code from @pad is what I would use, because I like to treat strings as immutable if possible. But I wouldn't use Char.escaped
; it's specialized for when you want the OCaml lexical representation of a character. So here's what you get if you make that change:
let prefix_char s c = String.make 1 c ^ s
let suffix_char s c = s ^ String.make 1 c
Update
In the years since this question was asked, OCaml has changed so that strings are immutable. Excellent.
String.make
and String.blit
is a good way to do so, but they seem to be imperative. Personally I prefer to make infix functions using Char.escaped
and string concatenation:
let (^$) c s = s ^ Char.escaped c (* append *)
let ($^) c s = Char.escaped c ^ s (* prepend *)
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