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?
相关问题
- how to split a list into a given number of sub-lis
- Generate string from integer with arbitrary base i
- Converting a string array to a byte array
- How to convert a string to a byte array which is c
- format ’%s’ expects argument of type ’char *’
相关文章
- JSP String formatting Truncate
- Selecting only the first few characters in a strin
- Is it possible to convert bitset<8> to char in c++
- Python: print in two columns
- extending c++ string member functions
- Google app engine datastore string encoding proble
- Bind a char to an enum type
- How to measure complexity of a string?
String.make
andString.blit
is a good way to do so, but they seem to be imperative. Personally I prefer to make infix functions usingChar.escaped
and string concatenation:I made a comparison of the efficiency of different approaches:
I wrote a simple test:
I compiled it natively (Intel Core 2 Duo).
I ran the test three times for each option, timing it with
time
, and calculating the mean real time elapsed.Here are the results:
s ^ String.make 1 c
: 7.75s (100%)s ^ Char.escaped c
: 8.30s (107%)Printf.sprintf "%s%c" s c
: 68.57s (885%)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:Update
In the years since this question was asked, OCaml has changed so that strings are immutable. Excellent.