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

From CodeCodex

m (Reverted edit of 219.138.204.162, changed back to last version by Why My Fleece?)
(Implementations)
Line 36: Line 36:
 
     s
 
     s
 
</HIGHLIGHTSYNTAX>
 
</HIGHLIGHTSYNTAX>
 +
 +
==Visual Basic===
 +
 +
<pre>
 +
sString = Replace(sString, " ", "")
 +
</pre>
  
 
[[Category:String]]
 
[[Category:String]]
Line 42: Line 48:
 
[[Category:Perl]]
 
[[Category:Perl]]
 
[[Category:Objective_Caml]]
 
[[Category:Objective_Caml]]
 +
[[Category:Visual Basic]]

Revision as of 23:25, 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=

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