String length: Difference between revisions
Content added Content deleted
(Use proper bullet syntax for Brainf*** explanations) |
(Added Stdlib-accessible OCaml version of UTF8 length) |
||
Line 2,319: | Line 2,319: | ||
7 |
7 |
||
5 |
5 |
||
</pre> |
|||
Alternatively, you can use the UChar module (available since OCaml 4.03) to do it without additional modules. |
|||
<syntaxhighlight lang="OCaml"> |
|||
let utf8_length (s: String.t) = |
|||
let byte_length = String.length s in |
|||
let rec count acc n = |
|||
if n = byte_length |
|||
then acc |
|||
else |
|||
let n' = n + (String.get_utf_8_uchar s n |> Uchar.utf_decode_length) in |
|||
count (succ acc) n' |
|||
in |
|||
count 0 0 |
|||
;; |
|||
</syntaxhighlight> |
|||
<pre> |
|||
# utf8_length "møøse" |
|||
- : int = 5 |
|||
</pre> |
</pre> |
||