From 0c624461d58d2b678cff6e61d72ce10b6277fedd Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 25 May 2015 00:04:48 +0200 Subject: [PATCH] add `CCString.set` for updating immutable strings --- src/core/CCString.cppo.ml | 10 ++++++++++ src/core/CCString.mli | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/src/core/CCString.cppo.ml b/src/core/CCString.cppo.ml index 36ed8936..246811bf 100644 --- a/src/core/CCString.cppo.ml +++ b/src/core/CCString.cppo.ml @@ -281,6 +281,16 @@ let unlines l = String.concat "\n" l let unlines_gen g = concat_gen ~sep:"\n" g +let set s i c = + if i<0 || i>= String.length s then invalid_arg "CCString.set"; + init (String.length s) (fun j -> if i=j then c else s.[j]) + +(*$T + set "abcd" 1 '_' = "a_cd" + set "abcd" 0 '-' = "-bcd" + (try set "abc" 5 '_'; false with Invalid_argument _ -> true) +*) + let pp buf s = Buffer.add_char buf '"'; Buffer.add_string buf s; diff --git a/src/core/CCString.mli b/src/core/CCString.mli index bf03f5e0..50c7f417 100644 --- a/src/core/CCString.mli +++ b/src/core/CCString.mli @@ -137,6 +137,12 @@ val unlines_gen : string gen -> string Q.printable_string (fun s -> unlines (lines s) = s) *) +val set : string -> int -> char -> string +(** [set s i c] creates a new string which is a copy of [s], except + for index [i], which becomes [c]. + @raise Invalid_argument if [i] is an invalid index + @since NEXT_RELEASE *) + include S with type t := string (** {2 Splitting} *)