Stdlib.String(3)
okay bestie, buckle up: this is Stdlib.String(3) from the OCaml library, aka the main-character string module. no cap, every signature, caveat, and tiny detail is staying exactly where it belongs ๐
โจ
๐ธ NAME ๐ธ
Stdlib.String โ literally โno descriptionโ in the original, and Iโm not inventing one ๐
๐งฉ Module ๐งฉ
Module Stdlib.String
๐ Documentation ๐
Module String : (module Stdlib__String)
๐ Strings ๐
type t = stringโ the type for strings. iconic. โจ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 -> (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.13val 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.5val of_bytes : bytes -> stringโ return a new string that contains the same bytes as the given byte sequence. ๐ฆ Since 4.13val to_bytes : string -> bytesโ return a new byte sequence that contains the same bytes as the given string. ๐ฅ Since 4.13val blit : string -> int -> bytes -> int -> int -> unitโ same asBytes.blit_string, which should be preferred. ๐ซถ
โจ Concatenating โจ
๐ Note. The (^) binary operator concatenates two strings.
val concat : 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.03 (4.05 in StringLabels)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.5val starts_with : prefix:string -> string -> boolโstarts_with ~prefix sistrueif and only ifsstarts withprefix. ๐ Since 4.13val ends_with : suffix:string -> string -> boolโends_with ~suffix sistrueif and only ifsends withsuffix. ๐ Since 4.13val 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.5val 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 -> int -> 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 โ๏ธ
okay so this is the splitting era, and yes every flavor is here ๐
๐ Splitting with magnitudes ๐
val take_first : int -> string -> stringโtake_first n sare the firstnbytes ofs. This issifn >= length sand""ifn <= 0. ๐ Since 5.5val take_last : int -> string -> stringโtake_last n sare the lastnbytes ofs. This issifn >= length sand""ifn <= 0. ๐ Since 5.5val drop_first : int -> string -> stringโdrop_first n sisswithout the firstnbytes ofs. This is""ifn >= length sandsifn <= 0. ๐ง Since 5.5val drop_last : int -> string -> stringโdrop_last n sisswithout the lastnbytes ofs. This is""ifn >= length sandsifn <= 0. ๐ง Since 5.5val cut_first : int -> string -> string * stringโcut_first n vis(take_first n v, drop_first n v). โจ Since 5.5val 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.5val take_last_while : (char -> bool) -> string -> stringโtake_last_while p sis the last consecutive bytes ofssatisfying the predicatep. ๐ธ Since 5.5val drop_first_while : (char -> bool) -> string -> stringโdrop_first_while p sisswithout the first consecutive bytes ofssatisfying the predicatep. ๐ฆ Since 5.5val drop_last_while : (char -> bool) -> string -> stringโdrop_last_while p sisswithout the last consecutive bytes ofssatisfying the predicatep. ๐ฆ Since 5.5val 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.5val 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 separatorsepins, orNoneifsepcanโt be found. Search forsepstarts at position0and usesString.find_first. Ifsepis"", this isSome ("", s). The invariantconcat sep [left; right] = sholds. โจ Since 5.5val 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 separatorsepins, orNoneifsepcanโt be found. Search forsepstarts at positionlength sand usesString.find_last. Ifsepis"", this isSome (s, ""). The invariantconcat sep [left; right] = sholds. โจ Since 5.5val 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 separatorsep, or the list[s]ifsepcanโt be found. Search forsepstarts at position0in increasing indexing order and usesString.find_all. Substringssubfor whichdrop subistrueare not included in the result.dropdefaults toFun.const false. Ifsepis"", this is[""; c0; ...; cn; ""]withcithe stringof_char s.[i]. The invariantconcat sep (split_all sep s) = sholds. ๐ฅ Since 5.5val 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 separatorsep, or[s]ifsepcanโt be found. Search forsepstarts at positionlength sin decreasing indexing order and usesString.rfind_all. Substringssubfor whichdrop subistrueare not included in the result.dropdefaults toFun.const false. Ifsepis"", this is[""; c0; ...; cn; ""]withcithe stringof_char s.[i]. The invariantconcat sep (rsplit_all sep s) = sholds. ๐ฅ Since 5.5val split_on_char : 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 the
sepcharacter. ๐ Since 4.04 (4.05 in StringLabels)
๐ฅ Transforming ๐ฅ
val map : (char -> char) -> string -> stringโmap f sis the string resulting from applyingfto all the characters ofsin increasing order. โญ Since 4.00val mapi : (int -> char -> char) -> string -> stringโmapi f sis likeString.mapbut the index of the character is also passed tof. โญ Since 4.02val fold_left : ('acc -> char -> 'acc) -> '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.13val fold_right : (char -> 'acc -> 'acc) -> string -> '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.13val for_all : (char -> bool) -> string -> boolโfor_all p schecks if all characters inssatisfy the predicatep. ๐ธ Since 4.13val exists : (char -> bool) -> string -> boolโexists p schecks if at least one character ofssatisfies the predicatep. ๐ธ Since 4.13val trim : string -> stringโtrim sisswithout leading and trailing whitespace. Whitespace characters are:' ','\x0C'(form feed),'\n','\r', and'\t'. ๐ Since 4.00val 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.03 (4.05 in StringLabels)val lowercase_ascii : string -> stringโlowercase_ascii sisswith all uppercase letters translated to lowercase, using the US-ASCII character set. ๐ Since 4.03 (4.05 in StringLabels)val capitalize_ascii : string -> stringโcapitalize_ascii sisswith the first character set to uppercase, using the US-ASCII character set. ๐
Since 4.03 (4.05 in StringLabels) โ uncapitalize_ascii is literally the lowercase-first-letter glow-up for a string ๐
val uncapitalize_ascii : string -> stringโuncapitalize_ascii sisswith the first character set to lowercase, using the US-ASCII character set. No cap, it's just that first char catching lowercase energy. โจ
๐ Traversing
val iter : (char -> unit) -> string -> unitโiter f sapplies functionfin turn to all the characters ofs. It is equivalent to:
f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()
val iteri : (int -> char -> unit) -> string -> unitโiteriis likeString.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.05val 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
๐ก 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. iykyk โ less repeated setup, more slay.
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 -> (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 -> (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
๐ก 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. Same energy, less repetitive setup.
val replace_first : sub:string -> by:string -> ?start:int -> string -> stringโreplace_first sub by start sreplaces bybythe first occurrence ofsubinsat 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 sreplaces bybythe last occurrence ofsubinsat 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 sreplaces bybyall non-overlapping occurrences ofsubinsat 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.07val to_seqi : t -> (int * char) Seq.tโto_seqi sis likeString.to_seqbut also tuples the corresponding index. Since 4.07val 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_dictwhoseString.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 listl, a suitableiter_dictis given by(fun yield -> List.iter yield l). All strings are assumed to be UTF-8 encoded, decoding errors are replaced byUchar.repcharacters. Since 5.4 ๐ซถ
๐งฎ Binary decoding of integers
The functions in this section binary decode integers from strings.
All following functions raise Invalid_argument if the characters needed at index i to decode the integer are not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. 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. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with int values.
val get_uint8 : string -> int -> intโget_uint8 b iisb's unsigned 8-bit integer starting at character indexi. Since 4.13val get_int8 : string -> int -> intโget_int8 b iisb's signed 8-bit integer starting at character indexi. Since 4.13val get_uint16_ne : string -> int -> intโget_uint16_ne b iisb's native-endian unsigned 16-bit integer starting at character indexi. Since 4.13val get_uint16_be : string -> int -> intโget_uint16_be b iisb's big-endian unsigned 16-bit integer starting at character indexi. Since 4.13val get_uint16_le : string -> int -> intโget_uint16_le b iisb's little-endian unsigned 16-bit integer starting at character indexi. Since 4.13val get_int16_ne : string -> int -> intโget_int16_ne b iisb's native-endian signed 16-bit integer starting at character indexi. Since 4.13val get_int16_be : string -> int -> intโget_int16_be b iisb's big-endian signed 16-bit integer starting at character indexi. Since 4.13val get_int16_le : string -> int -> int
val get_int16_le : string -> int -> int16
get_int16_le b i pulls the little-endian signed 16-bit integer sitting at character index i in b. ๐
Little-endian means the smallest byte comes first โ she's quirky like that.
Since 4.13
val get_int32_ne : string -> int -> int32
get_int32_ne b i is b's native-endian 32-bit integer starting at character index i. Native-endian = whatever your machine woke up feeling today, bestie ๐ซถ so don't go assuming, iykyk.
Since 4.13
val hash : t -> int
An unseeded hash function for strings, and the tea is it gives the exact same output value as Hashtbl.hash. โจ The whole point? It lets this module get passed as an argument to the functor Hashtbl.Make. Matching energy, no cap.
Since 5.0
val seeded_hash : int -> t -> int
A seeded hash function for strings, output value identical to Hashtbl.seeded_hash. ๐ Same deal โ this is what lets this module be passed as an argument to the functor Hashtbl.MakeSeeded. Seeded besties stay winning.
Since 5.0
val get_int32_be : string -> int -> int32
get_int32_be b i is b's big-endian 32-bit integer starting at character index i. Big-endian: biggest byte first, main character energy ๐.
Since 4.13
val get_int32_le : string -> int -> int32
get_int32_le b i is b's little-endian 32-bit integer starting at character index i. Tiny byte goes first, we stan a humble queen ๐.
Since 4.13
val get_int64_ne : string -> int -> int64
get_int64_ne b i is b's native-endian 64-bit integer starting at character index i. Bigger number, same chaotic energy โ it just matches your platform's vibe ๐.
Since 4.13
val get_int64_be : string -> int -> int64
get_int64_be b i is b's big-endian 64-bit integer starting at character index i. Sixty-four whole bits, big end first, absolutely serving ๐.
Since 4.13
val get_int64_le : string -> int -> int64
get_int64_le b i is b's little-endian 64-bit integer starting at character index i. Last but never least โ little-end first, forever iconic ๐.
Since 4.13
And that's a wrap on the whole page, bestie!! ๐ฆ This lil masterpiece was brought to you by OCamldoc, dated 2026-06-22, living at Stdlib.String(3). Go forth and read them 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