View Category

Output a string to the console

Write the string "Hello World!" to STDOUT
ocaml
print_string "Hello world!\n";;
print_endline "Hello world!";;
Printf.printf "Hello world!\n";;

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
ocaml
let query =
Netencoding.Url.mk_url_encoded_parameters [
"mode", "view";
"fname", "Ron & Jean";
"lname", "Smith";
]

let url =
"http://myserver.com/custinfo/edit.php?" ^ query

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
ocaml
let wrapper margin =
let cur = ref 0 in
fun word ->
let len = String.length word in
let beginning_of_line () =
Printf.printf "> %s" word;
cur := len + 2 in
if !cur = 0 then
beginning_of_line ()
else begin
cur := !cur + 1 + len;
if !cur <= margin then
Printf.printf " %s" word
else begin
print_newline ();
beginning_of_line ()
end
end

let wrap_string wrapper s =
let len = String.length s in
let rec aux_out i =
if i < len then
match s.[i] with
| ' ' | '\t' | '\n' ->
aux_out (i+1)
| _ -> aux_in i (i+1)
and aux_in i0 i =
if i >= len then
wrapper (String.sub s i0 (len - i0))
else match s.[i] with
| ' ' | '\t' | '\n' ->
wrapper (String.sub s i0 (i - i0));
aux_out (i+1)
| _ ->
aux_in i0 (i+1) in
aux_out 0

let () =
let base_string = "The quick brown fox jumps over the lazy dog. " in
let w = wrapper 78 in
for i = 1 to 10 do
wrap_string w base_string
done;
print_newline ()

Define a string containing special characters

Define the literal string "\#{'}${"}/"
ocaml
"\\#{'}${\"}/"

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
ocaml
"This\nIs\nA\nMultiline\nString"
"This
Is
A
Multiline
String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
ocaml
Printf.printf "%d+%d=%d" a b (a+b);;
Printf.printf "%d+%d=%d" a b (a+b);;

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
ocaml
let reverse str =
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
let j = pred len - i in
res.[i] <- str.[j]
done;
(res)
let rev_char str =
let l = Str.split (Str.regexp "") str in
List.fold_left (fun a b -> b ^ a) "" l
;;

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
ocaml
let rev_words str =
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.rev l)
;;

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
ocaml
(* ocamlbuild -no-hygiene textwrap.native && ./textwrap.native *)

let wrap s prefix width =
let width = width - (String.length prefix) in
let len = String.length s in
let rec loop start =
if start >= len then
[]
else
let stop = min (len - start) width in
let sub = String.sub s start stop in
(prefix ^ sub) :: loop (start+stop)
in
loop 0
in

let wrap_and_print s prefix width =
List.iter print_endline (wrap s prefix width)
in
let s = ref "" in
for i = 1 to 10 do
s := !s ^ "The quick brown fox jumps over the lazy dog. "
done;
wrap_and_print !s "> " 78


Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
ocaml
let left_pos s len =
let rec aux i =
if i >= len then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i)
| _ -> Some i
in
aux 0

let right_pos s len =
let rec aux i =
if i < 0 then None
else match s.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (pred i)
| _ -> Some i
in
aux (pred len)

let trim s =
let len = String.length s in
match left_pos s len, right_pos s len with
| Some i, Some j -> String.sub s i (j - i + 1)
| None, None -> ""
| _ -> assert false

let () =
let res = trim " hello " in
print_endline res
String.trim " hello "

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
ocaml
let rot_char13 c = match c with
| 'A'..'M' | 'a'..'m' -> Char.chr ((Char.code c) + 13)
| 'N'..'Z' | 'n'..'z' -> Char.chr ((Char.code c) - 13)
| _ -> c

let rot_char47 c = match c with
| '!'..'N' -> Char.chr ((Char.code c) + 47)
| 'O'..'~' -> Char.chr ((Char.code c) - 47)
| _ -> c

let rot f str =
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
res.[i] <- f str.[i]
done;
(res)

let rot13 = rot rot_char13
let rot47 = rot rot_char47

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
ocaml
String.uppercase "Space Monkey";;

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
ocaml
String.lowercase "Caps ARE overRated";;

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
ocaml
let capitalize_words str =
let len = String.length str in
let res = String.copy str in
let rec aux i do_up =
if i >= len then res else
match str.[i] with
| ' ' | '\n' | '\t' | '\r' -> aux (succ i) true
| _ ->
res.[i] <-
(if do_up then Char.uppercase else Char.lowercase) str.[i];
aux (succ i) false
in
aux 0 true

let () =
print_endline (capitalize_words "man OF stEEL")
let capitalize_words str =
let capitalize_word w =
String.capitalize (String.lowercase w) in
let l = Str.split (Str.regexp " ") str in
String.concat " " (List.map (capitalize_word) l)
;;


let () =
print_endline (capitalize_words "man OF stEEL");;