View Problem

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
DiskEdit
ruby
puts " hello ".strip
DiskEdit
ruby
" hello ".strip!
ExpandDiskEdit
java
String s = " hello "; String trimmed = s.trim();
DiskEdit
perl
my $string = " hello ";
$string =~ s{
\A\s* # Any number of spaces at the start of the string
(.+?) # Remember any number of characters until we reach
\s*\z # any number of spaces at the end of the string
}{
$1 # Leave the characters we remembered
}x;
DiskEdit
perl
my $string = " hello ";
$string =~ s{\A\s*}{};
$string =~ s{\s*\z}{};

DiskEdit
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
DiskEdit
groovy
assert "hello" == " hello ".trim()
ExpandDiskEdit
scala
val s = " hello ".trim
DiskEdit
python
assert 'hello' == ' hello '.strip()
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ s = " hello "; String^ trimmed = s->Trim();
ExpandDiskEdit
fsharp
let s = " hello "
let trimmed = s.Trim()
ExpandDiskEdit
fsharp
let trimmed = " hello ".Trim()
ExpandDiskEdit
erlang
Trimmed = string:strip(S),
DiskEdit
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
DiskEdit
ocaml 4.00.0
String.trim " hello "
ExpandDiskEdit
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
ExpandDiskEdit
php
$hello_trimmed = trim(" hello ");
DiskEdit
haskell
unwords (words " hello ")
DiskEdit
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
DiskEdit
clojure 1.3
(clojure.string/trim " hello ")
DiskEdit
clojure
(.trim " hello ")
ExpandDiskEdit
fantom
s := " hello ".trim
ExpandDiskEdit
go
s := strings.TrimSpace(" hello ")

Submit a new solution for ruby, java, perl, groovy ...