Module Base.String
An extension of the standard StringLabels. If you open Base, you'll get these extensions in the String module.
include Sexpable.S with type t := t
val t_of_sexp : Sexplib0.Sexp.t -> tval sexp_of_t : t -> Sexplib0.Sexp.t
include Container.S0 with type t := t with type elt = char
val length : t -> intval is_empty : t -> boolval iter : t -> f:(elt -> unit) -> unititermust allow exceptions raised infto escape, terminating the iteration cleanly. The same holds for all functions below taking anf.
val fold : t -> init:'accum -> f:('accum -> elt -> 'accum) -> 'accumfold t ~init ~freturnsf (... f (f (f init e1) e2) e3 ...) en, wheree1..enare the elements oft.
val fold_result : t -> init:'accum -> f:('accum -> elt -> ('accum, 'e) Result.t) -> ('accum, 'e) Result.tfold_result t ~init ~fis a short-circuiting version offoldthat runs in theResultmonad. Iffreturns anError _, that value is returned without any additional invocations off.
val fold_until : t -> init:'accum -> f:('accum -> elt -> ('accum, 'final) Base__.Container_intf.Continue_or_stop.t) -> finish:('accum -> 'final) -> 'finalfold_until t ~init ~f ~finishis a short-circuiting version offold. IffreturnsStop _the computation ceases and results in that value. IffreturnsContinue _, the fold will proceed. Iffnever returnsStop _, the final result is computed byfinish.Example:
type maybe_negative = | Found_negative of int | All_nonnegative of { sum : int } (** [first_neg_or_sum list] returns the first negative number in [list], if any, otherwise returns the sum of the list. *) let first_neg_or_sum = List.fold_until ~init:0 ~f:(fun sum x -> if x < 0 then Stop (Found_negative x) else Continue (sum + x)) ~finish:(fun sum -> All_nonnegative { sum }) ;; let x = first_neg_or_sum [1; 2; 3; 4; 5] val x : maybe_negative = All_nonnegative {sum = 15} let y = first_neg_or_sum [1; 2; -3; 4; 5] val y : maybe_negative = Found_negative -3
val exists : t -> f:(elt -> bool) -> boolReturns
trueif and only if there exists an element for which the provided function evaluates totrue. This is a short-circuiting operation.
val for_all : t -> f:(elt -> bool) -> boolReturns
trueif and only if the provided function evaluates totruefor all elements. This is a short-circuiting operation.
val count : t -> f:(elt -> bool) -> intReturns the number of elements for which the provided function evaluates to true.
val sum : (module Base__.Container_intf.Summable with type t = 'sum) -> t -> f:(elt -> 'sum) -> 'sumReturns the sum of
f ifor alliin the container.
val find : t -> f:(elt -> bool) -> elt optionReturns as an
optionthe first element for whichfevaluates to true.
val find_map : t -> f:(elt -> 'a option) -> 'a optionReturns the first evaluation of
fthat returnsSome, and returnsNoneif there is no such element.
val to_list : t -> elt listval to_array : t -> elt arrayval min_elt : t -> compare:(elt -> elt -> int) -> elt optionReturns a min (resp. max) element from the collection using the provided
comparefunction. In case of a tie, the first element encountered while traversing the collection is returned. The implementation usesfoldso it has the same complexity asfold. ReturnsNoneiff the collection is empty.
include Identifiable.S with type t := t
val hash_fold_t : Hash.state -> t -> Hash.stateval hash : t -> Hash.hash_value
include Sexpable.S with type t := t
val t_of_sexp : Sexplib0.Sexp.t -> tval sexp_of_t : t -> Sexplib0.Sexp.t
include Comparable.S with type t := t
include Base__.Comparable_intf.Polymorphic_compare
val ascending : t -> t -> intascendingis identical tocompare.descending x y = ascending y x. These are intended to be mnemonic when used likeList.sort ~compare:ascendingandList.sort ~cmp:descending, since they cause the list to be sorted in ascending or descending order, respectively.
val descending : t -> t -> intval between : t -> low:t -> high:t -> boolbetween t ~low ~highmeanslow <= t <= high
val clamp_exn : t -> min:t -> max:t -> tclamp_exn t ~min ~maxreturnst', the closest value totsuch thatbetween t' ~low:min ~high:maxis true.Raises if
not (min <= max).
val clamp : t -> min:t -> max:t -> t Or_error.t
include Comparator.S with type t := t
val comparator : (t, comparator_witness) Comparator.comparator
include Base__.Comparable_intf.Validate with type t := t
val validate_lbound : min:t Maybe_bound.t -> t Validate.checkval validate_ubound : max:t Maybe_bound.t -> t Validate.checkval validate_bound : min:t Maybe_bound.t -> max:t Maybe_bound.t -> t Validate.check
val length : t -> intval get : t -> int -> charval unsafe_get : string -> int -> charunsafe_get t iis likeget t ibut does not perform bounds checking. The caller must ensure that it is a memory-safe operation.
val make : int -> char -> tval copy : t -> tAssuming you haven't passed -unsafe-string to the compiler, strings are immutable, so there'd be no motivation to make a copy.
val init : int -> f:(int -> char) -> tval (^) : t -> t -> tString append. Also available unqualified, but re-exported here for documentation purposes.
Note that
a ^ bmust copy bothaandbinto a newly-allocated result string, soa ^ b ^ c ^ ... ^ zis quadratic in the number of strings.String.concatdoes not have this problem -- it allocates the result buffer only once.
val concat : ?sep:t -> t list -> tConcatenates all strings in the list using separator
sep(with a default separator"").
val escaped : t -> tSpecial characters are represented by escape sequences, following the lexical conventions of OCaml.
val contains : ?pos:int -> ?len:int -> t -> char -> boolval uppercase : t -> tOperates on the whole string using the US-ASCII character set, e.g.
uppercase "foo" = "FOO".
val lowercase : t -> tval capitalize : t -> tOperates on just the first character using the US-ASCII character set, e.g.
capitalize "foo" = "Foo".
module Caseless : sig ... endCaselesscompares and hashes strings ignoring case, so that for exampleCaseless.equal "OCaml" "ocaml"andCaseless.("apple" < "Banana")aretrue.
val index : t -> char -> int optionindex_exnandindex_from_exnraiseCaml.Not_foundorNot_found_swhencharcannot be found ins.
val index_exn : t -> char -> intval index_from : t -> int -> char -> int optionval index_from_exn : t -> int -> char -> intval rindex : t -> char -> int optionrindex_exnandrindex_from_exnraiseCaml.Not_foundorNot_found_swhencharcannot be found ins.
val rindex_exn : t -> char -> intval rindex_from : t -> int -> char -> int optionval rindex_from_exn : t -> int -> char -> int
module Search_pattern : sig ... endSubstring search and replace functions. They use the Knuth-Morris-Pratt algorithm (KMP) under the hood.
val substr_index : ?pos:int -> t -> pattern:t -> int optionSubstring search and replace convenience functions. They call
Search_pattern.createand then forget the preprocessed pattern when the search is complete.pos < 0orpos >= length tresult in no match (hencesubstr_indexreturnsNoneandsubstr_index_exnraises).may_overlapindicates whether to report overlapping matches, seeSearch_pattern.index_all.
val substr_index_exn : ?pos:int -> t -> pattern:t -> intval substr_index_all : t -> may_overlap:bool -> pattern:t -> int listval substr_replace_first : ?pos:int -> t -> pattern:t -> with_:t -> tval substr_replace_all : t -> pattern:t -> with_:t -> tAs with
Search_pattern.replace_all, the result may still containpattern.
val is_substring_at : t -> pos:int -> substring:t -> boolis_substring_at "foo bar baz" ~pos:4 ~substring:"bar"is true.
val to_list_rev : t -> char listReturns the reversed list of characters contained in a list.
val lsplit2_exn : t -> on:char -> t * tIf the string
scontains the characteron, thenlsplit2_exn s ~onreturns a pair containingssplit around the first appearance ofon(from the left). RaisesCaml.Not_foundorNot_found_swhenoncannot be found ins.
val rsplit2_exn : t -> on:char -> t * tIf the string
scontains the characteron, thenrsplit2_exn s ~onreturns a pair containingssplit around the first appearance ofon(from the right). RaisesCaml.Not_foundorNot_found_swhenoncannot be found ins.
val lsplit2 : t -> on:char -> (t * t) optionlsplit2 s ~onoptionally returnsssplit into two strings around the first appearance ofonfrom the left.
val rsplit2 : t -> on:char -> (t * t) optionrsplit2 s ~onoptionally returnsssplit into two strings around the first appearance ofonfrom the right.
val split : t -> on:char -> t listsplit s ~onreturns a list of substrings ofsthat are separated byon. Consecutiveoncharacters will cause multiple empty strings in the result. Splitting the empty string returns a list of the empty string, not the empty list.
val split_on_chars : t -> on:char list -> t listsplit_on_chars s ~onreturns a list of all substrings ofsthat are separated by one of the chars fromon.onare not grouped. So a grouping ofonin the source string will produce multiple empty string splits in the result.
val split_lines : t -> t listsplit_lines treturns the list of lines that compriset. The lines do not include the trailing"\n"or"\r\n".
val lfindi : ?pos:int -> t -> f:(int -> char -> bool) -> int optionlfindi ?pos t ~freturns the smallesti >= possuch thatf i t.[i], if there is such ani. By default,pos = 0.
val rfindi : ?pos:int -> t -> f:(int -> char -> bool) -> int optionrfindi ?pos t ~freturns the largesti <= possuch thatf i t.[i], if there is such ani. By defaultpos = length t - 1.
val lstrip : ?drop:(char -> bool) -> t -> tlstrip ?drop sreturns a string with consecutive chars satisfyingdrop(by default white space, e.g. tabs, spaces, newlines, and carriage returns) stripped from the beginning ofs.
val rstrip : ?drop:(char -> bool) -> t -> trstrip ?drop sreturns a string with consecutive chars satisfyingdrop(by default white space, e.g. tabs, spaces, newlines, and carriage returns) stripped from the end ofs.
val strip : ?drop:(char -> bool) -> t -> tstrip ?drop sreturns a string with consecutive chars satisfyingdrop(by default white space, e.g. tabs, spaces, newlines, and carriage returns) stripped from the beginning and end ofs.
val map : t -> f:(char -> char) -> tval mapi : t -> f:(int -> char -> char) -> tLike
map, but passes each character's index tofalong with the char.
val foldi : t -> init:'a -> f:(int -> 'a -> char -> 'a) -> 'afoldiworks similarly tofold, but also passes the index of each character tof.
val concat_map : ?sep:t -> t -> f:(char -> t) -> tLike
map, but allows the replacement of a single character with zero or two or more characters.
val filter : t -> f:(char -> bool) -> tfilter s ~f:predicatediscards characters not satisfyingpredicate.
val tr : target:char -> replacement:char -> t -> ttr ~target ~replacement sreplaces every instance oftargetinswithreplacement.
val tr_multi : target:t -> replacement:t -> (t -> t) Staged.ttr_multi ~target ~replacementreturns a function that replaces every instance of a character intargetwith the corresponding character inreplacement.If
replacementis shorter thantarget, it is lengthened by repeating its last character. Emptyreplacementis illegal unlesstargetalso is.If
targetcontains multiple copies of the same character, the last correspondingreplacementcharacter is used. Note that character ranges are not supported, so~target:"a-z"means the literal characters'a','-', and'z'.
val chop_suffix_exn : t -> suffix:t -> tchop_suffix_exn s ~suffixreturnsswithout the trailingsuffix, raisingInvalid_argumentifsuffixis not a suffix ofs.
val chop_prefix_exn : t -> prefix:t -> tchop_prefix_exn s ~prefixreturnsswithout the leadingprefix, raisingInvalid_argumentifprefixis not a prefix ofs.
val chop_suffix : t -> suffix:t -> t optionval chop_prefix : t -> prefix:t -> t optionval chop_suffix_if_exists : t -> suffix:t -> tchop_suffix_if_exists s ~suffixreturnsswithout the trailingsuffix, or justsifsuffixisn't a suffix ofs.Equivalent to
chop_suffix s ~suffix |> Option.value ~default:s, but avoids allocating the intermediate option.
val chop_prefix_if_exists : t -> prefix:t -> tchop_prefix_if_exists s ~prefixreturnsswithout the leadingprefix, or justsifprefixisn't a prefix ofs.Equivalent to
chop_prefix s ~prefix |> Option.value ~default:s, but avoids allocating the intermediate option.
val suffix : t -> int -> tsuffix s nreturns the longest suffix ofsof length less than or equal ton.
val prefix : t -> int -> tprefix s nreturns the longest prefix ofsof length less than or equal ton.
val drop_suffix : t -> int -> tdrop_suffix s ndrops the longest suffix ofsof length less than or equal ton.
val drop_prefix : t -> int -> tdrop_prefix s ndrops the longest prefix ofsof length less than or equal ton.
val concat_array : ?sep:t -> t array -> tconcat_array sep arlikeString.concat, but operates on arrays.
val hash : t -> intSlightly faster hash function on strings.
module Escaping : sig ... endOperations for escaping and unescaping strings, with parameterized escape and escapeworthy characters. Escaping/unescaping using this module is more efficient than using Pcre. Benchmark code can be found in core/benchmarks/string_escaping.ml.