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

From CodeCodex

(Implementations)
(Visual Basic=)
Line 40: Line 40:
  
 
<pre>
 
<pre>
sString = Replace(sString, " ", "")
+
To remove leading and trailing spaces from a string:
 +
 
 +
    sString = Trim(sString)
 +
 
 +
To remove all spaces from a string:
 +
 
 +
    sString = Replace(sString, " ", "")
 
</pre>
 
</pre>
  

Revision as of 23:27, 8 October 2007

Implementations

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 = test.input(); // output = "xyz" </HIGHLIGHTSYNTAX>

Perl

<HIGHLIGHTSYNTAX language="perl">

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

</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>

Visual Basic=

To remove leading and trailing spaces from a string:

    sString = Trim(sString)

To remove all spaces from a string:

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