Binary strings: Difference between revisions

added OCaml
(added OCaml)
Line 497:
strReplace old new orig = subRegex (mkRegex old) orig new
</lang>
 
=={{header|OCaml}}==
 
* String creation and destruction
 
<code>String.create n</code> returns a fresh string of length n, which initially contains arbitrary characters:
<lang ocaml># String.create 10 ;;
- : string = "\000\023\000\000\001\000\000\000\000\000"</lang>
 
No destruction, OCaml features a garbage collector.
 
OCaml strings can contain any of the 256 possible bytes included the null character '\000'.
 
* String assignment
<lang ocaml># let str = "some text" ;;
val str : string = "some text"
 
(* modifying a character, OCaml strings are mutable *)
# str.[0] <- 'S' ;;
- : unit = ()</lang>
 
* String comparison
<lang ocaml># str = "Some text" ;;
- : bool = true
 
# "Hello" > "Ciao" ;;
- : bool = true</lang>
 
* String cloning and copying
<lang ocaml># String.copy str ;;
- : string = "Some text"</lang>
 
* Check if a string is empty
<lang ocaml># let string_is_empty s = (s = "") ;;
val string_is_empty : string -> bool = <fun>
 
# string_is_empty str ;;
- : bool = false
 
# string_is_empty "" ;;
- : bool = true</lang>
 
* Append a byte to a string
 
it is not possible to append a byte to a string,
in the sens modifying the length of a given string,
but we can use the concatenation operator to append
a byte and return the result as a new string
 
<lang ocaml># str ^ "!" ;;
- : string = "Some text!"</lang>
 
But OCaml has a module named Buffer for string buffers.
This module implements string buffers that automatically expand as necessary. It provides accumulative concatenation of strings in quasi-linear time (instead of quadratic time when strings are concatenated pairwise).
 
<lang ocaml>Buffer.add_char str c</lang>
 
* Extract a substring from a string
<lang ocaml># String.sub str 5 4 ;;
- : string = "text"</lang>
 
* Replace every occurrence of a byte (or a string) in a string with another string
using the '''Str''' module
<lang ocaml># #load "str.cma";;
# let replace str occ by =
Str.global_replace (Str.regexp_string occ) by str
;;
val replace : string -> string -> string -> string = <fun>
# replace "The white dog let out a single, loud bark." "white" "black" ;;
- : string = "The black dog let out a single, loud bark."</lang>
 
* Join strings
<lang ocaml># "Now just remind me" ^ " how the horse moves again?" ;;
- : string = "Now just remind me how the horse moves again?"</lang>
 
 
=={{header|Python}}==