Trimming (computer programming): Difference between revisions

Content deleted Content added
mNo edit summary
moved
Tag: blanking
Line 36:
 
==Usage==
{{Main|Comparison_of_programming_languages_(string_functions)#trim}}
Following are examples of trimming a string using several programming languages. All of the implementations shown return a new string and do not alter the original variable.
 
{| class="wikitable"
|- style="text-align:left;"
! Example usage !! Languages
|-
| <tt>''String''.Trim([''chars''])</tt>
|[[C Sharp (programming language)|C#]], [[VB.NET]], [[Windows PowerShell]]
|-
| <tt>''string''.strip();</tt>
|[[D (programming language)|D]]
|-
| <tt>(.trim ''string'')</tt>
|[[Clojure]]
|-
|<tt>''sequence'' [ predicate? ] trim</tt>
|[[Factor (programming language)|Factor]]
|-
| <tt>(string-trim '(#\Space #\Tab #\Newline) ''string'')</tt>
|[[Common Lisp]]
|-
| <tt>(string-trim ''string'')</tt>
|[[Scheme (programming language)|Scheme]]
|-
| <tt>''string''.trim()</tt>
|[[Java (programming language)|Java]], [[JavaScript]] (1.8.1+, Firefox 3.5+)
|-
| <tt>Trim(''String'')</tt>
|[[Pascal (programming language)|Pascal]],<ref>{{cite web|url=http://gnu-pascal.de/gpc-hr/Trim.html |title=Trim - GNU Pascal priručnik |publisher=Gnu-pascal.de |date= |accessdate=2013-08-24}}</ref> [[QBasic]], [[Visual Basic]], [[Delphi programming language|Delphi]]
|-
| <tt>''string''.strip()</tt>
|[[Python (programming language)|Python]]
|-
| <tt>strings.Trim(''string'', ''chars'')</tt>
|[[Go (programming language)|Go]]
|-
| <tt>LTRIM(RTRIM(''String''))</tt>
|[[Oracle Corporation|Oracle]] [[SQL]], [[T-SQL]]
|-
| <tt>strip(''string'' [,''option'', ''char''])</tt>
|[[REXX (programming language)|REXX]]
|-
| <tt>string:strip(''string'' [,''option'', ''char''])</tt>
|[[Erlang (programming language)|Erlang]]
|-
| <tt>''string''.strip or ''string''.lstrip or ''string''.rstrip</tt>
|[[Ruby (programming language)|Ruby]]
|-
| <tt>''string'' =~ s/^\s+//r =~ s/\s+$//r</tt>
|[[Perl 5]]
|-
| <tt>''string''.trim</tt>
|[[Perl 6]]
|-
| <tt>trim(''string'')</tt>
|[[PHP]]
|-
| <tt>[''string'' stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]</tt>
|[[Objective-C]] using [[Cocoa (API)|Cocoa]]
|-
| <tt>''string'' withBlanksTrimmed<br>''string'' withoutSpaces<br>''string'' withoutSeparators</tt>
|[[Smalltalk]] (Squeak, Pharo)<br>[[Smalltalk]]
|-
|<tt>strip(string)</tt>
|[[SAS System|SAS]]
|-
|<tt>string trim ''$string''</tt>
|[[Tcl]]
|-
| <tt>TRIM(''string'') or TRIM(ADJUSTL(''string''))</tt>
|[[Fortran]]
|-
| <tt>TRIM(''string'')</tt>
|[[SQL]]
|-
| <tt>TRIM(''string'') or LTrim(''string'') or RTrim(''String'')</tt>
|[[ColdFusion]]
|-
| <tt>String.trim ''string''</tt>
|[[OCaml]] 4+
|}
 
===Other languages===
In languages without a built-in trim function, it is usually simple to create a custom function which accomplishes the same task.
 
====AWK====
In [[AWK programming language|AWK]], one can use regular expressions to trim:
 
<source lang="awk">
ltrim(v) = gsub(/^[ \t]+/, "", v)
rtrim(v) = gsub(/[ \t]+$/, "", v)
trim(v) = ltrim(v); rtrim(v)
</source>
 
or:
 
<source lang="awk">
function ltrim(s) { sub(/^[ \t]+/, "", s); return s }
function rtrim(s) { sub(/[ \t]+$/, "", s); return s }
function trim(s) { return rtrim(ltrim(s)); }
</source>
 
====C/C++====
There is no standard trim function in C or C++. Most of the available string libraries<ref>{{cite web|url=http://www.and.org/vstr/comparison |title=String library comparison |publisher=And.org |date= |accessdate=2013-08-24}}</ref> for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been called '''EatWhitespace''' in some non-standard C libraries.
 
In C, programmers often combine a ltrim and rtrim to implement trim:
 
<source lang="C">
#include <string.h>
#include <ctype.h>
 
void rtrim(char *str)
{
char *s;
s = str + strlen(str);
while (--s >= str) {
if (!isspace(*s)) break;
*s = 0;
}
}
 
void ltrim(char *str)
{
size_t n;
n = 0;
while (str[n] != '\0' && isspace((unsigned char)str[n])) {
n++;
}
memmove(str, str + n, strlen(str) - n + 1);
}
 
void trim(char *str)
{
rtrim(str);
ltrim(str);
}
</source>
 
The [[open-source software|open source]] C++ library [[Boost library|Boost]] has several trim variants, including a standard one:<ref>{{cite web|url=http://www.boost.org/doc/html/string_algo/usage.html#id2742817 |title=Usage - 1.54.0 |publisher=Boost.org |date=2013-05-22 |accessdate=2013-08-24}}</ref>
 
<source lang="cpp">
#include <boost/algorithm/string/trim.hpp>
trimmed = boost::algorithm::trim_copy("string");
</source>
 
Note that with boost's function named simply <code>trim</code> the input sequence is modified in-place, and does not return a result.
 
Another [[open-source software|open source]] C++ library [[Qt (toolkit)|Qt]] has several trim variants, including a standard one:<ref>[http://doc.trolltech.com/4.5/qstring.html#trimmed] {{wayback|url=http://doc.trolltech.com/4.5/qstring.html#trimmed |date=20090802041055 }}</ref>
 
<source lang="cpp-qt">
#include <QString>
trimmed = s.trimmed();
</source>
 
The [[Linux kernel]] also includes a strip function, <code>strstrip()</code>, since 2.6.18-rc1, which trims the string "in place". Since 2.6.33-rc1, the kernel uses <code>strim()</code> instead of <code>strstrip()</code> to avoid false warnings.<ref>[https://github.com/dankamongmen/sprezzos-kernel-packaging/blob/master/changelog]</ref>
 
====Haskell====
A trim algorithm in [[Haskell (programming language)|Haskell]]:
 
<source lang="haskell">
import Data.Char (isSpace)
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
</source>
 
may be interpreted as follows: ''f'' drops the preceding whitespace, and reverses the string. ''f'' is then again applied to its own output. Note that the type signature (the second line) is optional.
 
====J====
 
The trim algorithm in [[J (programming language)|J]] is a [[functional programming|functional]] description:
 
<source lang="J">
trim =. #~ [: (+./\ *. +./\.) ' '&~:
</source>
 
That is: filter (<code>#~</code>) for non-space characters (<code>' '&~:</code>) between leading (<code>+./\</code>) and (<code>*.</code>) trailing (<code>+./\.</code>) spaces.
 
====JavaScript====
There is a built-in trim function in JavaScript 1.8.1 (Firefox 3.5 and later), and the ECMAScript 5 standard. In earlier versions it can be added to the String object's prototype as follows:
 
<source lang="javascript">
String.prototype.trim = function() {
return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
};
</source>
 
====Perl====
Perl 5 has no built-in trim function. However, the functionality is commonly achieved using [[regular expression]]s.
 
Example:
<source lang="perl">
$string =~ s/^\s+//; # remove leading whitespace
$string =~ s/\s+$//; # remove trailing whitespace
</source>
or:
<source lang="perl">
$string =~ s/^\s+|\s+$//g ; # remove both leading and trailing whitespace
</source>
These examples modify the value of the original variable <code>$string</code>.
 
Also available for Perl is '''StripLTSpace''' in <code>String::Strip</code> from [[CPAN]].
 
There are, however, two functions that are commonly used to strip whitespace from the end of strings, <code>chomp</code> and <code>chop</code>:
* <code>[http://perldoc.perl.org/functions/chop.html chop]</code> removes the last character from a string and returns it.
* <code>[http://perldoc.perl.org/functions/chomp.html chomp]</code> removes the trailing newline character(s) from a string if present. (What constitutes a newline is [http://perldoc.perl.org/perlvar.html $INPUT_RECORD_SEPARATOR] dependent).
 
In [[Perl 6]], the upcoming major revision of the language, strings have a <code>trim</code> method.
 
Example:
<source lang="perl">
$string = $string.trim; # remove leading and trailing whitespace
$string .= trim; # same thing
</source>
 
====Tcl====
The [[Tcl]] <code>string</code> command has three relevant subcommands: <code>trim</code>, <code>trimright</code> and <code>trimleft</code>. For each of those commands, an additional argument may be specified: a string that represents a set of characters to remove—the default is whitespace (space, tab, newline, carriage return).
 
Example of trimming vowels:
 
<source lang="tcl">
set string onomatopoeia
set trimmed [string trim $string aeiou] ;# result is nomatop
set r_trimmed [string trimright $string aeiou] ;# result is onomatop
set l_trimmed [string trimleft $string aeiou] ;# result is nomatopoeia
</source>
 
====XSLT====
[[XSL Transformations|XSLT]] includes the function <code>normalize-space(''string'')</code> which strips leading and trailing whitespace, in addition to replacing any whitespace sequence (including line breaks) with a single space.
 
Example:
<source lang="xml">
<xsl:variable name='trimmed'>
<xsl:value-of select='normalize-space(string)'/>
</xsl:variable>
</source>
XSLT 2.0 includes regular expressions, providing another mechanism to perform string trimming.
 
Another XSLT technique for trimming is to utilize the XPath 2.0 <code>substring()</code> function.
 
==See also==