Stdlib.StringLabels(3)
π Stdlib.StringLabels π
okay bestie, welcome to the Stdlib.StringLabels page from the OCaml library β the manual literally has Stdlib.StringLabels(3) sitting up top, but weβre folding that name in right here so youβre oriented π
. This page is long, so itβs part 1 of 3 (more incoming, donβt panic).
β¨ NAME β¨
Stdlib.StringLabels - no description
π§© Module π§©
Module Stdlib.StringLabels
π Documentation π
Module StringLabels : (module Stdlib__StringLabels)
π§΅ Strings π§΅
type t = stringβ the type for strings. periodt πval make : int -> char -> stringβmake n cis a string of lengthnwith each index holding the characterc.
β οΈ RaisesInvalid_argumentifn < 0orn > Sys.max_string_length.
val init : int -> f:(int -> char) -> stringβinit n ~fis a string of lengthnwith indexiholding the characterf i(called in increasing index order).
Since 4.02 β¨
β οΈ RaisesInvalid_argumentifn < 0orn > Sys.max_string_length.
val empty : stringβ the empty string.
Since 4.13 π
val length : string -> intβlength sis the length (number of bytes/characters) ofs.val get : string -> int -> charβget s iis the character at indexiins. This is the same as writings.[i].
β οΈ RaisesInvalid_argumentifinot an index ofs.
val of_char : char -> stringβof_char ciscas a string.
Since 5.5 π¦
val of_bytes : bytes -> stringβ return a new string that contains the same bytes as the given byte sequence.
Since 4.13 πΈ
val to_bytes : string -> bytesβ return a new byte sequence that contains the same bytes as the given string.
Since 4.13 π
val blit : src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unitβ same asBytes.blit_stringwhich should be preferred.
π Concatenating π
note: The (^) binary operator concatenates two strings.
val concat : sep:string -> string list -> stringβconcat ~sep ssconcatenates the list of stringsss, inserting the separator stringsepbetween each.
β οΈ RaisesInvalid_argumentif the result is longer thanSys.max_string_lengthbytes.
val cat : string -> string -> stringβcat s1 s2concatenatess1ands2(s1 ^ s2).
Since 4.13 β
β οΈ RaisesInvalid_argumentif the result is longer thanSys.max_string_lengthbytes.
π΅οΈ Predicates and comparisons π΅οΈ
val equal : t -> t -> boolβequal s0 s1istrueif and only ifs0ands1are character-wise equal.
Since 4.05 π
val compare : t -> t -> intβcompare s0 s1sortss0ands1in lexicographical order.comparebehaves likecompareon strings but may be more efficient.val is_empty : string -> boolβis_empty sistrueif and only ifsis an empty string.
Since 5.5 π§
val starts_with : prefix:string -> string -> boolβstarts_with ~prefix sistrueif and only ifsstarts withprefix.
Since 4.13 π
val ends_with : suffix:string -> string -> boolβends_with ~suffix sistrueif and only ifsends withsuffix.
Since 4.13 π
val includes : affix:string -> string -> boolβincludes ~affix sistrueif and only ifaffixoccurs ins.
note: To test the sameaffixstring multiple times, partially applying the~affixargument and using the resulting function repeatedly is more efficient.
Since 5.5 π
val contains_from : string -> int -> char -> boolβcontains_from s start cistrueif and only ifcappears insafter positionstart.
β οΈ RaisesInvalid_argumentifstartis not a valid position ins.
val rcontains_from : string -> int -> char -> boolβrcontains_from s stop cistrueif and only ifcappears insbefore positionstop+1.
β οΈ RaisesInvalid_argumentifstop < 0orstop+1is not a valid position ins.
val contains : string -> char -> boolβcontains s cisString.contains_from s 0 c.
βοΈ Extracting substrings βοΈ
val sub : string -> pos:int -> len:int -> stringβsub s ~pos ~lenis a string of lengthlen, containing the substring ofsthat starts at positionposand has lengthlen.
β οΈ RaisesInvalid_argumentifposandlendo not designate a valid substring ofs.
π° Splitting strings π°
π§ Splitting with magnitudes π§
val take_first : int -> string -> stringβtake_first n sare the firstnbytes ofs. This issifn >= length sand""ifn <= 0.
Since 5.5 π
val take_last : int -> string -> stringβtake_last n sare the lastnbytes ofs. This issifn >= length sand""ifn <= 0.
Since 5.5 π
val drop_first : int -> string -> stringβdrop_first n sisswithout the firstnbytes ofs. This is""ifn >= length sandsifn <= 0.
Since 5.5 π
val drop_last : int -> string -> stringβdrop_last n sisswithout the lastnbytes ofs. This is""ifn >= length sandsifn <= 0.
Since 5.5 π
val cut_first : int -> string -> string * stringβcut_first n vis(take_first n v, drop_first n v).
Since 5.5 π
val cut_last : int -> string -> string * stringβcut_last n vis(drop_last n v, take_last n v).
Since 5.5 π
π§ Splitting with predicates π§
val take_first_while : (char -> bool) -> string -> stringβtake_first_while p sis the first consecutive bytes ofssatisfying the predicatep.
Since 5.5 π¦
val take_last_while : (char -> bool) -> string -> stringβtake_last_while p sis the last consecutive bytes ofssatisfying the predicatep.
Since 5.5 π¦
val drop_first_while : (char -> bool) -> string -> stringβdrop_first_while p sisswithout the first consecutive bytes ofssatisfying the predicatep.
Since 5.5 π¦
val drop_last_while : (char -> bool) -> string -> stringβdrop_last_while p sisswithout the last consecutive bytes ofssatisfying the predicatep.
Since 5.5 π¦
val cut_first_while : (char -> bool) -> string -> string * stringβcut_first_while p sis(take_first_while p s, drop_first_while p s).
Since 5.5 π¦
val cut_last_while : (char -> bool) -> string -> string * stringβcut_last_while p sis(drop_last_while p s, take_last_while p s).
Since 5.5 π¦
π§ Splitting with separators π§
note: To split the samesepstring multiple times, partially applying the~separgument of these functions and using the resulting function repeatedly is more efficient.
val split_first : sep:string -> string -> (string * string) optionβsplit_first ~sep sis the pairSome (left, right)made of the two (possibly empty) substrings ofsthat are delimited by the first match of the separatorsepinsorNoneifsepcan't be found. Search forsepstarts at position0and usesStringLabels.find_first.
If sep is "", this is Some ("", s).
The invariant concat sep [left; right] = s holds.
Since 5.5 π«
val split_last : sep:string -> string -> (string * string) optionβsplit_last ~sep sis the pairSome (left, right)made of the two (possibly empty) substrings ofsthat are delimited by the last match of the separatorsepinsorNoneifsepcan't be found. Search forsepstarts at positionlength sand usesStringLabels.find_last.
If sep is "", this is Some (s, "").
The invariant concat sep [left; right] = s holds.
Since 5.5 π«
val split_all : sep:string -> ?drop:(string -> bool) -> string -> string listβsplit_all ~sep sis the list of all substrings ofsthat are delimited by non-overlapping matches of the separatorsepor the list[s]ifsepcan't be found. Search forsepstarts at position0in increasing indexing order and usesStringLabels.find_all.
Substrings sub for which drop sub is true are not included in the result. drop defaults to Fun.const false.
If sep is "", this is [""; c0; ...; cn; ""] with ci the string of_char s.[i].
The invariant concat sep (split_all ~sep s) = s holds.
Since 5.5 π«
val rsplit_all : sep:string -> ?drop:(string -> bool) -> string -> string listβrsplit_all ~sep sis the list of all substrings ofsthat are delimited by non-overlapping matches of the separatorsepor[s]ifsepcan't be found. Search forsepstarts at positionlength sin decreasing indexing order and usesStringLabels.rfind_all.
Substrings sub for which drop sub is true are not included in the result. drop defaults to Fun.const false.
If sep is "", this is [""; c0; ...; cn; ""] with ci the string of_char s.[i].
The invariant concat sep (rsplit_all ~sep s) = s holds.
Since 5.5 π«
val split_on_char : sep:char -> string -> string listβsplit_on_char ~sep sis the list of all (possibly empty) substrings ofsthat are delimited by the charactersep. Ifsis empty, the result is the singleton list[""].
The function's result is specified by the following invariants:
-The list is not empty.
-Concatenating its elements using sep as a separator returns a string equal to the input ( concat (make 1 sep)
(split_on_char sep s) = s ).
-No string in the result contains the sep character.
Since 4.05 π
π Transforming π
val map : f:(char -> char) -> string -> stringβmap f sis the string resulting from applyingfto all the characters ofsin increasing order.
Since 4.00 β¨
val mapi : f:(int -> char -> char) -> string -> stringβmapi ~f sis likeStringLabels.mapbut the index of the character is also passed tof.
Since 4.02 β¨
val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> string -> 'accβfold_left f x scomputesf (... (f (f x s.[0]) s.[1]) ...) s.[n-1], wherenis the length of the strings.
Since 4.13 π
val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'accβfold_right f s xcomputesf s.[0] (f s.[1] ( ... (f s.[n-1] x) ...)), wherenis the length of the strings.
Since 4.13 π
val for_all : f:(char -> bool) -> string -> boolβfor_all p schecks if all characters inssatisfy the predicatep.
Since 4.13 π
val exists : f:(char -> bool) -> string -> boolβexists p schecks if at least one character ofssatisfies the predicatep.
Since 4.13 π
val trim : string -> stringβtrim sisswithout leading and trailing whitespace. Whitespace characters are:' ','\x0C'(form feed),'\n','\r', and'\t'.
Since 4.00 β¨
val escaped : string -> stringβescaped sisswith special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x5C) and double-quote (0x22).
The function Scanf.unescaped is a left inverse of escaped, i.e. Scanf.unescaped (escaped s) = s for any string s (unless escaped s fails).
β οΈ RaisesInvalid_argumentif the result is longer thanSys.max_string_lengthbytes.
val uppercase_ascii : string -> stringβuppercase_ascii sisswith all lowercase letters translated to uppercase, using the US-ASCII character set.
Since 4.05 π
val lowercase_ascii : string -> stringβlowercase_ascii sisswith all uppercase letters translated to lowercase, using the US-ASCII character set.
Since 4.05 π
val capitalize_ascii : string -> string
capitalize_ascii s is s but with its very first character bumped up to uppercase, US-ASCII rules only π
nothing fancy, no Unicode drama.
Since 4.05
val uncapitalize_ascii : string -> stringβuncapitalize_ascii sisswith the first character knocked down to lowercase, again strictly US-ASCII. π
Since 4.05
π¦ Traversing π¦
val iter : f:(char -> unit) -> string -> unitβiter ~f sruns your functionfover every single character ofs, one after another, no skips. It's literally the same vibe asf s.[0]; f s.[1]; ...; f s.[length s - 1]; ()β¨val iteri : f:(int -> char -> unit) -> string -> unitβiteriis exactly likeStringLabels.iter, except your function also gets handed the matching character index, so you always know where you are πΊοΈ
Since 4.00
π Finding indices π
val find_first_index : (char -> bool) -> ?start:int -> string -> int optionβfind_first_index p ~start sgives you the index of the first character ofsthat passes your predicatep, at or after the index (or position)start, which defaults to0. π
If start is length s, the answer is always None. No cap.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val find_last_index : (char -> bool) -> ?start:int -> string -> int optionβfind_last_index p ~start sgives you the index of the last character ofsthat satisfiesp, at or before the index (or position)start, which defaults tolength s. πΈ
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val index_from : string -> int -> char -> intβindex_from s i cis the index of the firstcinsidesafter positioni. π―
Raises Not_found if c justβ¦ isn't in s after position i π
Raises Invalid_argument if i isn't a valid position in s.
val index_from_opt : string -> int -> char -> int optionβindex_from_opt s i cis the index of the firstcinsafter positioni(if there even is one π). Same thing as above but it won't throw hands at you.
Since 4.05
Raises Invalid_argument if i isn't a valid position in s.
val rindex_from : string -> int -> char -> intβrindex_from s i cis the index of the lastcinsbefore positioni+1. Going backwards, queen behavior π
Raises Not_found if c doesn't occur in s before position i+1.
Raises Invalid_argument if i+1 isn't a valid position in s.
val rindex_from_opt : string -> int -> char -> int optionβrindex_from_opt s i cis the index of the lastcinsbefore positioni+1(if any π«Ά).
Since 4.05
Raises Invalid_argument if i+1 isn't a valid position in s.
val index : string -> char -> intβindex s cis literally justString.index_from s 0 c. Shortcut city βval index_opt : string -> char -> int optionβindex_opt s cisString.index_from_opt s 0 c. The chill version π¦
Since 4.05
val rindex : string -> char -> intβrindex s cisString.rindex_from s (length s - 1) c. Backwards search from the very end, iconic.val rindex_opt : string -> char -> int optionβrindex_opt s cisString.rindex_from_opt s (length s - 1) c. Same but with theoptionsafety net π
Since 4.05
π§ Finding substrings π§
Note. If you're hunting for the same substring multiple times, partially applying the ~sub argument of these functions and then reusing the resulting function is more efficient. Do less work, slay more π
val find_first : sub:string -> ?start:int -> string -> int optionβfind_first ~sub ~start sis the starting position of the first occurrence ofsubins, at or after the index (or position)start, which defaults to0. π₯
If sub is "", the result is Some start. And heads up: the result of the function is always a valid index of s, except when sub is "" and start is length s. That one little edge case, iykyk π
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val find_last : sub:string -> ?start:int -> string -> int optionβfind_last ~sub ~start sis the starting position of the last occurrence ofsubins, at or before the index (or position)start, which defaults toString.length s. πΈ
If sub is "", the result is Some start. Same fine print as above: the result is always a valid index of s except when sub is "" and start is length s.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val find_all : sub:string -> f:(int -> 'acc -> 'acc) -> ?start:int -> string -> 'acc -> 'accβfind_all ~sub f ~start s accstarts fromaccand foldsfin increasing index order over all the non-overlapping starting positions ofsubins, at or after the index (or position)start, which defaults to0. Ifsubnever shows up ins, you just getaccback, no harm no foul π«Ά
If sub is "", then f gets invoked on all positions of s at or after start.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val rfind_all : sub:string -> f:(int -> 'acc -> 'acc) -> ?start:int -> string -> 'acc -> 'accβrfind_all ~sub f ~start s accstarts fromaccand foldsfin decreasing index order over all the non-overlapping starting positions ofsubins, at or before the index (or position)start, which defaults toString.length s. Stillaccif nothing's found π
If sub is "", then f gets invoked on all positions of s at or before start.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
π Replacing substrings π
Note. Same efficiency tip as before: replacing the same substring over and over? Partially apply the ~sub argument of these functions and reuse the resulting function repeatedly. Obsessed with the efficiency β¨
val replace_first : sub:string -> by:string -> ?start:int -> string -> stringβreplace_first ~sub ~by ~start sswapsbyin for the first occurrence ofsubins, at or after the index (or position)start, which defaults to0. πͺ
If sub is "", this inserts by at position start.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val replace_last : sub:string -> by:string -> ?start:int -> string -> stringβreplace_last ~sub ~by ~start sreplacesbyby the last occurrence ofsubins, at or after the index (or position)start, which defaults toString.length s. (Yes, that's exactly how the original says it βbygoes in wheresubwas, don't overthink it π)
If sub is "", this inserts by at position start.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
val replace_all : sub:string -> by:string -> ?start:int -> string -> stringβreplace_all ~sub ~by ~start sreplaces every non-overlapping occurrence ofsubinswithby, at or after the index (or position)start, which defaults to0. Occurrences get found in increasing indexing order, left to right, methodical queen π
If sub is "", this inserts by at all positions from start on.
Since 5.5
Raises Invalid_argument if start isn't a valid position of s.
π Strings and Sequences π
val to_seq : t -> char Seq.tβto_seq sis a sequence built from the string's characters, in increasing order. Easy. Gorgeous. π¦
Since 4.07
val to_seqi : t -> (int * char) Seq.tβto_seqi sis likeStringLabels.to_seq, but it also tuples up the matching index with each character. Best of both worlds π
Since 4.07
val of_seq : char Seq.t -> tβof_seq sis a string made out of the sequence's characters. Sequence in, string out. Iconic. β
Since 4.07
π§΅ UTF decoding and validations π§΅
π UTF-8 π
val get_utf_8_uchar : t -> int -> Uchar.utf_decodeβget_utf_8_uchar b idecodes a UTF-8 character sitting at indexiinb. πval is_valid_utf_8 : t -> boolβis_valid_utf_8 bistrueif and only ifbholds valid UTF-8 data. No cap, it really checks β
π UTF-16BE π
val get_utf_16be_uchar : t -> int -> Uchar.utf_decodeβget_utf_16be_uchar b idecodes a UTF-16BE character at indexiinb. πval is_valid_utf_16be : t -> boolβis_valid_utf_16be bistrueif and only ifbcontains valid UTF-16BE data. π«Ά
πΈ UTF-16LE πΈ
val get_utf_16le_uchar : t -> int -> Uchar.utf_decodeβget_utf_16le_uchar b idecodes a UTF-16LE character at indexiinb. πval is_valid_utf_16le : t -> boolβis_valid_utf_16le bistrueif and only ifbcontains valid UTF-16LE data. π
β¨ Spellchecking β¨
val edit_distance : ?limit:int -> t -> t -> intβedit_distance s0 s1is the number of single-character edits (insertion, deletion, substitution, transposition β the whole glow-up menu) needed to turns0intos1. π
If you pass limit, the function bails and returns limit the moment it's determined that s0 and s1 are at least limit apart. That's faster when you've got a fixed limit β like, say, for spellchecking π
Heads up on the encoding: the function assumes the strings are UTF-8 encoded and uses Uchar.t for its notion of "character". Decoding errors get replaced by Uchar.rep. And normalizing your strings to NFC gives better results, so do that π
Note. This implements the simpler Optimal String Alignment (OSA) distance, not the Damerau-Levenshtein distance. Which means with this function"ca"and"abc"have a distance of3, not2. Fr fr, don't @ me π
Since 5.4
val spellcheck : ?max_dist:(string -> int) -> ((string -> unit) -> unit) -> string -> string listβspellcheck iter_dict sgives you the strings enumerated by the iteratoriter_dictwhoseStringLabels.edit_distancetosis the smallest and at mostmax_dist s. If multiple corrections come back, their order is as found initer_dictβ respect the source order π«Ά
The default max_dist s is:
0ifshas 0 to 2 Unicode characters.1ifshas 3 to 4 Unicode characters.2otherwise.
If your dictionary happens to be a list l, a suitable iter_dict is given by (fun yield -> List.iter yield l). Chef's kiss π€
All strings are assumed to be UTF-8 encoded, and decoding errors are replaced by Uchar.rep characters.
Since 5.4
π₯ Binary decoding of integers π₯
The functions in this section binary decode integers from strings. Yes, we're going full low-level, and honestly? It slaps.
All the following functions raise Invalid_argument if the characters needed at index i to decode the integer aren't available. π
Little-endian (resp. big-endian) encoding means that the least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order β that's the one your networking friends keep bringing up. Native-endian encoding is either little-endian or big-endian depending on Sys.big_endian. π
32-bit and 64-bit integers are represented by the int32 and int64 types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the int type, which has more bits than the binary encoding. Those extra bits are sign-extended (or zero-extended) for functions that decode 8-bit or 16-bit integers and represent them with int values. Tiny numbers, big shoes π
val get_uint8 : string -> int -> intβget_uint8 b iisb's unsigned 8-bit integer starting at character indexi. π―
Since 4.13
val get_int8 : string -> int -> intβget_int8 b iisb's signed 8-bit integer starting at character indexi. π―
Since 4.13
val get_uint16_ne : string -> int -> intβget_uint16_ne b iisb's native-endian unsigned 16-bit integer starting at character indexi. π
Since 4.13
val get_uint16_be : string -> int -> intβget_uint16_be b iisb's big-endian unsigned 16-bit integer starting at character indexi. π
Since 4.13
val get_uint16_le : string -> int -> intβget_uint16_le b iisb's little-endian unsigned 16-bit integer starting at character indexi. π
Since 4.13
val get_int16_ne : string -> int -> intβget_int16_ne b iisb's native-endian signed 16-bit integer starting at character indexi. π
Since 4.13
val get_int16_be : string -> int -> int
Okay so these next ones are the byte-decoding girlies β they read raw integers straight out of a string at a character index. Same shape every time: you hand them the string b and an index i, they hand you back a number. Obsessed. π
val get_int16_be : string -> int -> intβget_int16_be b iisb's big-endian signed 16-bit integer starting at character indexi. π
Since 4.13
val get_int16_le : string -> int -> intβget_int16_le b iisb's little-endian signed 16-bit integer starting at character indexi. π
Since 4.13
val get_int32_ne : string -> int -> int32βget_int32_ne b iisb's native-endian 32-bit integer starting at character indexi. Bestie, native-endian is literally "whatever your machine feels like," iykyk. π
Since 4.13
Okay plot twist β the doc just casually drops the hash functions here in the middle of the endian-ness parade. Not me getting whiplash π but slay, we keep the original order, always. β¨
val hash : t -> intβ an unseeded hash function for strings, with the same output value asHashtbl.hash. The whole point? It lets this module be passed as an argument to the functorHashtbl.Make. π
Since 5.0
val seeded_hash : int -> t -> intβ a seeded hash function for strings, with the same output value asHashtbl.seeded_hash. And this one lets this module be passed as an argument to the functorHashtbl.MakeSeeded. π«Ά
Since 5.0
And we're back to the endian content, no notes. π¦
val get_int32_be : string -> int -> int32βget_int32_be b iisb's big-endian 32-bit integer starting at character indexi. β
Since 4.13
val get_int32_le : string -> int -> int32βget_int32_le b iisb's little-endian 32-bit integer starting at character indexi. β
Since 4.13
val get_int64_ne : string -> int -> int64βget_int64_ne b iisb's native-endian 64-bit integer starting at character indexi. Big number energy π₯
Since 4.13
val get_int64_be : string -> int -> int64βget_int64_be b iisb's big-endian 64-bit integer starting at character indexi. π₯
Since 4.13
val get_int64_le : string -> int -> int64βget_int64_le b iisb's little-endian 64-bit integer starting at character indexi. π₯
Since 4.13
And that's the whole page bestie!! ππ You made it to the end of part three, which honestly deserves a little reward. Go drink some water. πΈ
That's a wrap from OCamldoc, dated 2026-06-22, covering Stdlib.StringLabels(3) β mwah, take care of her π«Άβ¨
π¦ where this page comes from
- arch rolling: ocaml 5.5.0-1 Β· LGPL2.1 AND custom: QPL-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms