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

From CodeCodex

(Visual Basic=)
(Implementations)
Line 38: Line 38:
  
 
===Visual Basic===
 
===Visual Basic===
 
+
To remove leading and/or trailing spaces from a string:
<pre>
+
<HIGHLIGHTSYNTAX language="visual_basic">
To remove leading and trailing spaces from a string:
+
    sString = LTrim(sString)          ' Remove leading spaces'
 
+
    sString = RTrim(sString)          ' Remove trailing spaces'
     sString = Trim(sString)
+
     sString = Trim(sString)           ' Remove leading and trailing spaces'
 +
</HIGHLIGHTSYNTAX>
  
 
To remove all spaces from a string:
 
To remove all spaces from a string:
 
+
<HIGHLIGHTSYNTAX language="visual_basic">
 
     sString = Replace(sString, " ", "")
 
     sString = Replace(sString, " ", "")
</pre>
+
</HIGHLIGHTSYNTAX>
  
 
[[Category:String]]
 
[[Category:String]]

Revision as of 23:37, 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/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>