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

From CodeCodex

(Blanked the page)
Line 1: Line 1:
{{Infobox See Also String}}
===Common Lisp===
Common lisp has a built-in string-trim function. In fact, you can get rid of arbitrary characters. The first parameter is the character you want to get rid of from the right and left of the string, the second parameter is the string.
(string-trim " " " trim me ")
;;output "trim me"
Unsurprisingly, if you want to just get rid of characters on just one end of the string, use string-right-trim or string-left-trim.
string:strip("  123 xyz  ").          % "123 xyz"
string:strip("  123 xyz  ", left).    % "123 xyz  "
string:strip("  123 xyz  ", right).    % "  123 xyz"
string:strip("...123 xyz..", both, $.). % "123 xyz"
The String class in Java has a built in trim function:
<pre class="java">
  String s = "  xyz  ".trim();
  System.out.println(s);  // prints out "xyz";
According to Java document:
<blockquote>If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned. </blockquote>
If you want to trim an empty character sequence "      " to "", trim() works (in this case, trim will return the empty string).
Trim is not built into JavaScript, but you can use prototyping to add this to your code:
<pre class="javascript">
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
Then you can use this code like this example:
<pre class="javascript">
var input = "  xyz  ";
var output = input.trim();    // output = "xyz"
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))
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
    search init
  let len = String.length str in
    let left = search_pos 0 (fun i -> i >= len) (succ)
    and right = search_pos (len - 1) (fun i -> i < 0) (pred)
    String.sub str left (right - left + 1)
  | Failure "empty" -> ""
s{\A\s*|\s*\z}{}gmsx; # remove leading and trailing whitespace
<pre class="php">
  $string = trim($string);
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 ('''L'''eft-strip); '''rstrip()''' removes trailing characters ('''R'''ight-strip).
<pre class="python">
"  xyz  ".strip()            # returns "xyz"
"  xyz  ".lstrip()          # returns "xyz  "
"  xyz  ".rstrip()          # returns "  xyz"
"  x y z  ".replace(' ', '')  # returns "xyz"
This is very similar to the python version above.
<pre class="ruby">
"    test 1  ".strip            #=> "test 1"
"    test 1  ".lstrip          #=> "test 1  "
"    test 1  ".rstrip          #=> "    test 1"
"    test 1  ".gsub(" ","")    #=> "test1"
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:
<pre class="vb">
    sString = LTrim(sString)          ' Remove leading spaces'
    sString = RTrim(sString)          ' Remove trailing spaces'
    sString = Trim(sString)          ' Remove leading and trailing spaces'
To remove all spaces from a string:
<pre class="vb">
    sString = Replace(sString, " ", "")
string="  123 abc xyz  "
${string// /} # output: 123abcxyz
[[Category:Common Lisp]]
[[Category:Visual Basic]]

Revision as of 11:48, 13 June 2012