StringLabels(3)
π NAME π
okay bestie, welcome to StringLabels(3) β the labeled-string module that's about to be your new fave. No cap, it's giving βstrings but make it labeledβ and we're gonna break it down together. β¨
π§ Module π§
Module StringLabels
: sig end
β¨ Documentation β¨
Module StringLabels
: sig end
Strings. π
A string s of length n is an indexable and immutable sequence of n bytes. For historical reasons these bytes are referred to as characters. (yes, bestie, bytes are getting called characters β it's a whole thing, just go with it π«Ά)
The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows.
positions 0 1 2 3 4 n-1 n +---+---+---+---+ +-----+
indices | 0 | 1 | 2 | 3 | ... | n-1 | +---+---+---+---+ +-----+
-An index i of s is an integer in the range [ 0 ; n-1 ]. It represents the i th byte (character) of s which can be accessed using the constant time string indexing operator s.[i] .
-A position i of s is an integer in the range [ 0 ; n ]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The i th byte index is between position i and i+1 .
Two integers start and len are said to define a valid substring of s if len >= 0 and start, start+len are positions of s.
Unicode text. Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string "\u{1F42B}" is the UTF-8 encoding of the Unicode character U+1F42B. π¦
Past mutability. Before OCaml 4.02, strings used to be modifiable in place like Bytes.t mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. π
The labeled version of this module can be used as described in the StdLabels module.
π Strings π
type t = stringβ The type for strings.val make : int -> char -> stringβmake n cis a string of lengthnwith each index holding the characterc.- Raises
Invalid_argumentifn < 0orn > Sys.max_string_length.
- Raises
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
- Raises
Invalid_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].- Raises
Invalid_argumentifinot an index ofs.
- Raises
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.- Raises
Invalid_argumentif the result is longer thanSys.max_string_lengthbytes.
- Raises
val cat : string -> string -> stringβcat s1 s2concatenatess1ands2(s1 ^ s2).- Since 4.13
- Raises
Invalid_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 same affix string multiple times, partially applying the
~affixargument and using the resulting function repeatedly is more efficient. - Since 5.5
- Note. To test the same affix string multiple times, partially applying the
val contains_from : string -> int -> char -> boolβcontains_from s start cistrueif and only ifcappears insafter positionstart.- Raises
Invalid_argumentifstartis not a valid position ins.
- Raises
val rcontains_from : string -> int -> char -> boolβrcontains_from s stop cistrueif and only ifcappears insbefore positionstop+1.- Raises
Invalid_argumentifstop < 0orstop+1is not a valid position ins.
- Raises
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.- Raises
Invalid_argumentifposandlendo not designate a valid substring ofs.
- Raises
π 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 same sep string multiple times, partially applying the ~sep argument 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
sepis"", this isSome ("", s). - The invariant
concat sep [left; right] = sholds. - Since 5.5
- If
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
sepis"", this isSome (s, ""). - The invariant
concat sep [left; right] = sholds. - Since 5.5
- If
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
subfor whichdrop subistrueare not included in the result.dropdefaults toFun.const false. - If
sepis"", this is[""; c0; ...; cn; ""]withcithe stringof_char s.[i]. - The invariant
concat sep (split_all ~sep s) = sholds. - Since 5.5
- Substrings
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
subfor whichdrop subistrueare not included in the result.dropdefaults toFun.const false. - If
sepis"", this is[""; c0; ...; cn; ""]withcithe stringof_char s.[i]. - The invariant
concat sep (rsplit_all ~sep s) = sholds. - Since 5.5
- Substrings
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
sepas 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 thesepcharacter. - Since 4.05
- The function's result is specified by the following invariants: -The list is not empty. -Concatenating its elements using
π₯ 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 -> 'accfold_left f x sβ computesf (... (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 every single character inssatisfies 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. The 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 functionScanf.unescapedis a left inverse ofescaped, i.e.Scanf.unescaped (escaped s) = sfor any strings(unlessescaped sfails). 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 sisswith the first character set to uppercase, using the US-ASCII character set. Since 4.05.val uncapitalize_ascii : string -> stringβuncapitalize_ascii sisswith the first character set to lowercase, using the US-ASCII character set. Since 4.05.
β¨ Traversing β¨
val iter : f:(char -> unit) -> string -> unitβiter ~f sapplies functionfin turn to all the characters ofs. It is equivalent tof s.[0]; f s.[1]; ...; f s.[length s - 1]; ().val iteri : f:(int -> char -> unit) -> string -> unitβiteriis likeStringLabels.iter, but the function is also given the corresponding character index. Since 4.00.
π Finding indices π
val find_first_index : (char -> bool) -> ?start:int -> string -> int optionβfind_first_index p ~start sis the index of the first character ofsthat satisfies predicatepat or after the index or positionstart(defaults to0). Ifstartislength s, the result is alwaysNone. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val find_last_index : (char -> bool) -> ?start:int -> string -> int optionβfind_last_index p ~start sis the index of the last character ofsthat satisfies predicatepat or before the index or positionstart(defaults tolength s). Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val index_from : string -> int -> char -> intβindex_from s i cis the index of the first occurrence ofcinsafter positioni. RaisesNot_foundifcdoes not occur insafter positioni. RaisesInvalid_argumentifiis not a valid position ins.val index_from_opt : string -> int -> char -> int optionβindex_from_opt s i cis the index of the first occurrence ofcinsafter positioni(if any). Since 4.05. RaisesInvalid_argumentifiis not a valid position ins.val rindex_from : string -> int -> char -> intβrindex_from s i cis the index of the last occurrence ofcinsbefore positioni+1. RaisesNot_foundifcdoes not occur insbefore positioni+1. RaisesInvalid_argumentifi+1is not a valid position ins.val rindex_from_opt : string -> int -> char -> int optionβrindex_from_opt s i cis the index of the last occurrence ofcinsbefore positioni+1(if any). Since 4.05. RaisesInvalid_argumentifi+1is not a valid position ins.val index : string -> char -> intβindex s cisString.index_from s 0 c.val index_opt : string -> char -> int optionβindex_opt s cisString.index_from_opt s 0 c. Since 4.05.val rindex : string -> char -> intβrindex s cisString.rindex_from s (length s - 1) c.val rindex_opt : string -> char -> int optionβrindex_opt s cisString.rindex_from_opt s (length s - 1) c. Since 4.05.
π Finding substrings π
Bestie note: to find the same sub string multiple times, partially applying the ~sub argument of these functions and using the resulting function repeatedly is more efficient.
val find_first : sub:string -> ?start:int -> string -> int optionβfind_first ~sub ~start sis the starting position of the first occurrence ofsubinsat or after the index or positionstart(defaults to0). Ifsubis""the result isSome start. The result of the function is always a valid index ofsexcept whensubis""andstartislength s. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val find_last : sub:string -> ?start:int -> string -> int optionβfind_last ~sub ~start sis the starting position of the last occurrence ofsubinsat or before the index or positionstart(defaults toString.length s). Ifsubis""the result isSome start. The result of the function is always a valid index ofsexcept whensubis""andstartislength s. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val find_all : sub:string -> f:(int -> 'acc -> 'acc) -> ?start:int -> string -> 'acc -> 'accβfind_all ~sub f ~start s acc, starting withacc, foldsfby increasing index order over all non-overlapping starting positions ofsubinsat or after the index or positionstart(defaults to0). The result isaccifsubcould not be found ins. Ifsubis"",fgets invoked on all positions ofsat or afterstart. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val rfind_all : sub:string -> f:(int -> 'acc -> 'acc) -> ?start:int -> string -> 'acc -> 'accβrfind_all ~sub f ~start s acc, starting withacc, foldsfby decreasing index order over all non-overlapping starting positions ofsubinsat or before the index or positionstart(defaults toString.length s). The result isaccifsubcould not be found ins. Ifsubis"",fgets invoked on all positions ofsat or beforestart. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.
π Replacing substrings π
Bestie note: to replace the same sub string multiple times, partially applying the ~sub argument of these functions and using the resulting function repeatedly is more efficient.
val replace_first : sub:string -> by:string -> ?start:int -> string -> stringβreplace_first ~sub ~by ~start sswaps the first occurrence ofsubinsforby, at or after the index or positionstart(defaults to0). Ifsubis"", this insertsbyat positionstart. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val replace_last : sub:string -> by:string -> ?start:int -> string -> stringβreplace_last ~sub ~by ~start sswaps the last occurrence ofsubinsforby, at or after the index or positionstart(defaults toString.length s). Ifsubis"", this insertsbyat positionstart. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.val replace_all : sub:string -> by:string -> ?start:int -> string -> stringβreplace_all ~sub ~by ~start sswaps every non-overlapping occurrence ofsubinsforby, at or after the index or positionstart(defaults to0). Occurrences are found in increasing indexing order. Ifsubis"", this insertsbyon all positions fromstarton. Since 5.5. RaisesInvalid_argumentifstartis not a valid position ofs.
π§΅ Strings and Sequences π§΅
val to_seq : t -> char Seq.tβto_seq sis a sequence made of the string's characters in increasing order. Since 4.07.val to_seqi : t -> (int * char) Seq.tβto_seqi sis likeStringLabels.to_seqbut also tuples the corresponding index. Since 4.07.val of_seq : char Seq.t -> tβof_seq sis a string made of the sequence's characters. 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 an UTF-8 character at indexiinb.val is_valid_utf_8 : t -> boolβis_valid_utf_8 bistrueif and only ifbcontains valid UTF-8 data.
π¦ UTF-16BE π¦
val get_utf_16be_uchar : t -> int -> Uchar.utf_decodeβget_utf_16be_uchar b idecodes an 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 an 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 (understood as insertion, deletion, substitution, transposition) that are needed to changes0intos1. Iflimitis provided the function returns withlimitas soon as it was determined thats0ands1have distance of at leastlimit. This is faster if you have a fixed limit, for example for spellchecking. The function assumes the strings are UTF-8 encoded and usesUchar.tfor the notion of character. Decoding errors are replaced byUchar.rep. Normalizing the strings to NFC gives better results.
Note: this implements the simpler Optimal String Alignment (OSA) distance, not the Damerau-Levenshtein distance. With this function"ca"and"abc"have a distance of3not2.
Since 5.4.
val spellcheck : ?max_dist:(string -> int) -> ((string -> unit) -> unit) -> string -> string listβspellcheck iter_dict sare the strings enumerated by the iteratoriter_dictwhoseStringLabels.edit_distancetosis the smallest and at mostmax_dist s. If multiple corrections are returned their order is as found initer_dict. The defaultmax_dist sis:0ifshas 0 to 2 Unicode characters.1ifshas 3 to 4 Unicode characters.2otherwise.
If your dictionary is a list l, a suitable iter_dict is given by (fun yield -> List.iter yield l). All strings are assumed to be UTF-8 encoded, 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.
Okay so before we get into the actual functions, there's some lore you need to know π
Every single function below raises Invalid_argument if the characters it needs at index i to decode the integer just... aren't there. Like if you're asking for 8 bytes starting at index 3 of a 5-char string, she will not be nice about it. π
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first β yes bestie, the byte order is literally the whole personality of the encoding. Big-endian is also known as network byte order (iykyk). Native-endian encoding is either little-endian or big-endian depending on Sys.big_endian β so it's giving "wherever you run it, that's the vibe" energy.
32-bit and 64-bit integers are represented by the int32 and int64 types, and they can be interpreted either as signed or unsigned numbers. Flexible icon behavior, honestly. β¨
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 which decode 8-bit or 16-bit integers and represented them with int values β think of it as padding out the outfit so it fits the bigger type π
the actual functions, let's go π
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β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. Since 4.13 πval hash : t -> intβ an unseeded hash function for strings, with the same output value asHashtbl.hash. This function allows this module to be passed as 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. This function allows this module to be passed as argument to the functorHashtbl.MakeSeeded. Since 5.0 π₯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. 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 π
Also ngl β some of these decoders are literally int*32* and int*64* island and int*16* land, and yes, they're giving "why isinthere doing overtime," but the manpage says what the manpage says. Go off,int. π
And that's a wrap on this page, bestie! π This was StringLabels(3), brought to you by OCamldoc, with a version date of 2026-06-22 β so print it out, put it on your wall, and go decode some bytes responsibly π«Άπβ¨
π¦ 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