Difference between revisions of "Trim whitespace (spaces) from a string"

From CodeCodex

(Implementations: add ruby)
(PHP)
Line 4: Line 4:
 
===PHP===
 
===PHP===
 
<highlightsyntax>
 
<highlightsyntax>
  $string = trim($string);
 
 
</highlightsyntax>
 
</highlightsyntax>
  

Revision as of 08:40, 16 April 2010

Implementations

PHP

<highlightsyntax> </highlightsyntax>

Java

The String class in Java has a built in trim function: <HIGHLIGHTSYNTAX language="java122">

 String s = "  xyz  ".trim();
 System.out.println(s);  // prints out "xyz";

</HIGHLIGHTSYNTAX>

JavaScript

Trim is not built into JavaScript, but you can use prototyping to add this to your code: <HIGHLIGHTSYNTAX language="javascript"> String.prototype.trim = function() {

  return this.replace(/^\s+|\s+$/g,"");

} </HIGHLIGHTSYNTAX> Then you can use this code like this example: <HIGHLIGHTSYNTAX language="javascript"> var input = " xyz "; var output = input.trim(); // output = "xyz" </HIGHLIGHTSYNTAX>

OCaml

<HIGHLIGHTSYNTAX language="ocaml"> let rec trim s =

 let l = String.length s in 
 if l=0 then s
 else if s.[0]=' ' || s.[0]='\t' || s.[0]='\n' || s.[0]='\r' then
   trim (String.sub s 1 (l-1))
 else if s.[l-1]=' ' || s.[l-1]='\t' || s.[l-1]='\n' || s.[l-1]='\r' then
   trim (String.sub s 0 (l-1))
 else
   s

</HIGHLIGHTSYNTAX>

another solution:

let trim str =
  if str = "" then "" else
  let search_pos init p next =
    let rec search i =
      if p i then raise(Failure "empty") else
      match str.[i] with
      | ' ' | '\n' | '\r' | '\t' -> search (next i)
      | _ -> i
    in
    search init
  in
  let len = String.length str in
  try
    let left = search_pos 0 (fun i -> i >= len) (succ)
    and right = search_pos (len - 1) (fun i -> i < 0) (pred)
    in
    String.sub str left (right - left + 1)
  with
  | Failure "empty" -> ""
;;

Perl

<HIGHLIGHTSYNTAX language="perl">

s{\A\s*|\s*\z}{}gmsx; # remove leading and trailing whitespace

</HIGHLIGHTSYNTAX>

Python

Python strings have the strip(), lstrip(), rstrip() methods for removing any character from both ends of a string. If the characters to be removed are not specified then whitespace will be removed. strip() removes from both ends; lstrip() removes leading characters (Left-strip); rstrip() removes trailing characters (Right-strip). <HIGHLIGHTSYNTAX language="python"> " xyz ".strip() # returns "xyz" " xyz ".lstrip() # returns "xyz " " xyz ".rstrip() # returns " xyz" " x y z ".replace(' ', ) # returns "xyz" </HIGHLIGHTSYNTAX>

Ruby

This is very similar to the python version above. <HIGHLIGHTSYNTAX language="ruby"> irb(main):001:0> test = " test " => " test " irb(main):002:0> test.strip => "test" irb(main):003:0> test.lstrip => "test " irb(main):004:0> test.rstrip => " test" </HIGHLIGHTSYNTAX>

Seed7

The trim function removes leading and trailing spaces and control chars:

writeln(trim("  xyz  ")); # writes the string "xyz";

Visual Basic

To remove leading and/or trailing spaces from a string: <HIGHLIGHTSYNTAX language="visual_basic">

   sString = LTrim(sString)          ' Remove leading spaces'
   sString = RTrim(sString)          ' Remove trailing spaces'
   sString = Trim(sString)           ' Remove leading and trailing spaces'

</HIGHLIGHTSYNTAX>

To remove all spaces from a string: <HIGHLIGHTSYNTAX language="visual_basic">

   sString = Replace(sString, " ", "")

</HIGHLIGHTSYNTAX>

Zsh

string="  123 abc xyz  "
${string// /} # output: 123abcxyz