View Problem
Remove leading and trailing whitespace from a string
Given the string
Submit a new solution for clojure, cpp, erlang, fantom ...
There are 2 other solutions in additional languages (csharp or go)
" 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
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
perl
#Modification History:
# 2009-MAR-17: GGARIEPY: [creation] (geoff.gariepy@gmail.com)
$string = " hello ";
$string =~ s/^\s+|\s+$//g; # All the action happens in one regex!
# Regex Notes:
# ^ - anchors to the beginning of the string
# $ - anchors to the end of the string
# g - causes regex to match as many times as possible
# | - logical OR
# 2009-MAR-17: GGARIEPY: [creation] (geoff.gariepy@gmail.com)
$string = " hello ";
$string =~ s/^\s+|\s+$//g; # All the action happens in one regex!
# Regex Notes:
# ^ - anchors to the beginning of the string
# $ - anchors to the end of the string
# g - causes regex to match as many times as possible
# | - logical OR
Submit a new solution for clojure, cpp, erlang, fantom ...
There are 2 other solutions in additional languages (csharp or go)




