Trimming (computer programming): Difference between revisions

Content deleted Content added
Haskell: Correct code.
m Bot: http → https
 
(41 intermediate revisions by 32 users not shown)
Line 1:
{{ManualRefimprove|date=February 20092015}}
 
In [[computer programming]], '''trimming''' ('''trim''') or '''stripping''' ('''strip''') is a [[string (computer science)|string manipulation]] in which leading and trailing [[whitespace (computer science)character|whitespace]] is removed from a [[string (computer science)|string]].
 
For example, the string (enclosed by apostrophes)
 
<sourcesyntaxhighlight lang=text>' this is a test '</sourcesyntaxhighlight>
 
would be changed, after trimming, to
 
<sourcesyntaxhighlight lang=text>'this is a test'</sourcesyntaxhighlight>
 
==Variants==
The most popular variants of the trim function strip only the beginning or end of the string. Typically named '''ltrim''' and '''rtrim''' respectively, or in the case of Python: '''lstrip''' and '''rstrip'''. C# uses '''TrimStart''' and '''TrimEnd''', and Common Lisp '''string-left-trim''' and '''string-right-trim'''. Pascal and Java do not have these variants built-in, although [[Object Pascal]] (Delphi) has '''TrimLeft''' and '''TrimRight''' functions.<ref>http://www.freepascal.org/docs-html/rtl/sysutils/trim.html</ref>
 
===Left or right trimming===
''Many trim functions have an optional parameter to specify a list of characters to trim, instead of the default whitespace characters. For example, PHP and Python allow this optional parameter, while Pascal and Java do not. With Common Lisp's <code>string-trim</code> function, the parameter (called ''character-bag'') is required. The C++ [[Boost library]] defines space characters according to [[locale]], as well as offering variants with a [[predicate (computer programming)|predicate]] parameter (a [[functor]]) to select which characters are trimmed.''
 
The most popular variants of the trim function strip only the beginning or end of the string. Typically named '''ltrim''' and '''rtrim''' respectively, or in the case of Python: '''lstrip''' and '''rstrip'''. C# uses '''TrimStart''' and '''TrimEnd''', and Common Lisp '''string-left-trim''' and '''string-right-trim'''. Pascal and Java do not have these variants built-in, although [[Object Pascal]] (Delphi) has '''TrimLeft''' and '''TrimRight''' functions.<ref>{{cite web|url=https://www.freepascal.org/docs-html/rtl/sysutils/trim.html |title=Trim |publisher=Freepascal.org |date=2013-02-02 |access-date=2013-08-24}}</ref>
An uncommon variant of trim returns a special result if no characters remain after the trim operation. For example, [[Jakarta Project|Apache Jakarta]]'s '''StringUtils''' has a function called <code>stripToNull</code> which returns <code>null</code> in place of an empty string.
 
===Whitespace character list parameterization===
An alternative to trimming a string is space normalization, where in addition to removing surrounding whitespace, any sequence of whitespace characters within the string is replaced with a single space. Space normalization is done by <code>Trim()</code> in spreadsheet applications (including [[Microsoft Excel|Excel]], [[OpenOffice.org Calc|Calc]], [[Gnumeric]], and [[Google Docs]]), and by the <code>normalize-space()</code> function in [[XSL Transformations|XSLT]] and [[XPath]],
 
Many trim functions have an optional parameter to specify a list of characters to trim, instead of the default whitespace characters. For example, PHP and Python allow this optional parameter, while Pascal and Java do not. With Common Lisp's <code>string-trim</code> function, the parameter (called ''character-bag'') is required. The C++ [[Boost library]] defines space characters according to [[Locale (computer software)|locale]], as well as offering variants with a [[predicate (computer programming)|predicate]] parameter (a [[functor]]) to select which characters are trimmed.
While most algorithms return a new (trimmed) string, some alter the original string [[in-place]]. Notably, the [[Boost library]] allows either in-place trimming or a trimmed copy to be returned.
 
===Special empty string return value===
==Definition of whitespace==
The characters which are considered whitespace varies between programming languages and implementations. For example, C traditionally only counts space, tab, line feed, and carriage return characters, while languages which support [[Unicode]] typically include all Unicode space characters. Some implementations also include [[ASCII]] control codes (non-printing characters) along with whitespace characters.
 
An uncommon variant of trim returns a special result if no characters remain after the trim operation. For example, [[Jakarta Project|Apache Jakarta]]'s '''StringUtils''' has a function called <code>stripToNull</code> which returns <code>null</code> in place of an empty string.
Java's trim method considers ASCII spaces and control codes as whitespace, while Java's <ref>http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isWhitespace(char) isWhitespace()</ref> method recognizes Unicode space characters.
 
===Space normalization===
Delphi's Trim function considers characters U+0000 (NULL) through U+0020 (SPACE) to be whitespace.
 
Space normalization is a related string manipulation where in addition to removing surrounding whitespace, any sequence of whitespace characters within the string is replaced with a single space. Space normalization is performed by the function named <code>Trim()</code> in spreadsheet applications (including [[Microsoft Excel|Excel]], [[OpenOffice.org Calc|Calc]], [[Gnumeric]], and [[Google Docs]]), and by the <code>normalize-space()</code> function in [[XSL Transformations|XSLT]] and [[XPath]],
==Usage==
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.
 
===In-place trimming===
{| class="wikitable"
|- align="left"
! Example usage !! Languages
|-
|''String''.Trim([''chars''])
|[[C Sharp (programming language)|C#]], [[VB.NET]], [[Windows PowerShell]]
|-
|''string''.strip();
|[[D (programming language)|D]]
|-
|(.trim ''string'')
|[[Clojure]]
|-
|-
|''sequence'' [ predicate? ] trim
|[[Factor (programming language)|Factor]]
|-
|(string-trim '(#\Space #\Tab #\Newline) ''string'')
|[[Common Lisp]]
|-
|(string-trim ''string'')
|[[Scheme (programming language)|Scheme]]
|-
|''string''.trim()
|[[Java (programming language)|Java]], [[JavaScript]] (1.8.1+, Firefox 3.5+)
|-
|Trim(''String'')
|[[Pascal (programming language)|Pascal]],<ref>http://gnu-pascal.de/gpc-hr/Trim.html</ref> [[QBasic]], [[Visual Basic]], [[Delphi programming language|Delphi]]
|-
|''string''.strip()
|[[Python (programming language)|Python]]
|-
|strings.Trim(''string'', ''chars'')
|[[Go (programming language)|Go]]
|-
|LTRIM(RTRIM(''String''))
|[[Oracle Corporation|Oracle]] [[SQL]], [[T-SQL]]
|-
|strip(''string'' [,''option'', ''char''])
|[[REXX (programming language)|REXX]]
|-
|string:strip(''string'' [,''option'', ''char''])
|[[Erlang (programming language)|Erlang]]
|-
|''string''.strip
|[[Ruby (programming language)|Ruby]]
|-
|(''string'' =~ /\S(.*\S)?/s, $&)
|[[Perl 5]]
|-
|''string''.trim
|[[Perl 6]]
|-
|trim(''string'')
|[[PHP]]
|-
|[''string'' stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
|[[Objective-C]] using [[Cocoa (API)|Cocoa]]
|-
|''string'' withBlanksTrimmed<br>''string'' withoutSpaces<br>''string'' withoutSeparators
|[[Smalltalk]] (Squeak, Pharo)<br>[[Smalltalk]]
|-
|strip(string)
|[[SAS System|SAS]]
|-
|string trim ''$string''
|[[Tcl]]
|-
|TRIM(''string'') or TRIM(ADJUSTL(''string''))
|[[Fortran]]
|-
|TRIM(''string'')
|[[SQL]]
|-
|TRIM(''string'') or LTrim(''string'') or RTrim(''String'')
|[[ColdFusion]]
|}
 
While most algorithms return a new (trimmed) string, some alter the original string [[in-place]]. Notably, the [[Boost library]] allows either in-place trimming or a trimmed copy to be returned.
===Other languages===
In languages without a built-in trim function, it is usually simple to create a custom function which accomplishes the same task.
 
==Definition of whitespace==
====AWK====
The characters which are considered whitespace varies between programming languages and implementations. For example, C traditionally only counts space, tab, line feed, and carriage return characters, while languages which support [[Unicode]] typically include all Unicode space characters. Some implementations also include [[ASCII]] control codes (non-printing characters) along with whitespace characters.
In [[AWK programming language|AWK]], one can use regular expressions to trim:
 
Java's trim method considers ASCII spaces and control codes as whitespace, contrasting with the Java <code>isWhitespace()</code> method,<ref>{{cite web|url=https://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isWhitespace(char) |title=Character (Java 2 Platform SE 5.0) |publisher=Java.sun.com |access-date=2013-08-24}}</ref> which recognizes all Unicode space characters.
<source lang="awk">
ltrim(v) = gsub(/^[ \t]+/, "", v)
rtrim(v) = gsub(/[ \t]+$/, "", v)
trim(v) = ltrim(v); rtrim(v)
</source>
 
Delphi's Trim function considers characters U+0000 (NULL) through U+0020 (SPACE) to be whitespace.
or:
 
=== Non-space blanks ===
<source lang="awk">
The [[Braille Patterns]] Unicode block contains {{unichar|2800|Braille pattern blank|html=}}, a [[Braille]] pattern with no dots raised.
function ltrim(s) { sub(/^[ \t]+/, "", s); return s }
The Unicode standard explicitly states that it does not act as a space.
function rtrim(s) { sub(/[ \t]+$/, "", s); return s }
function trim(s) { return rtrim(ltrim(s)); }
</source>
 
The [[Non-breaking space]] {{unichar|00A0|NO-BREAK SPACE|html=}} can also be treated as non-space for trimming purposes.
====C/C++====
There is no standard trim function in C or C++. Most of the available string libraries<ref>http://www.and.org/vstr/comparison</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.
 
==Usage==
In C, programmers often combine a ltrim and rtrim to implement trim:
{{Main|Comparison of programming languages (string functions)#trim}}
 
==References==
<source lang="C">
{{Reflist}}
char *
rtrim(char *str)
{
char *ptr;
int len;
 
len = strlen(str);
for (ptr = str + len - 1; ptr >= str && isspace((int)*ptr ); --ptr);
 
ptr[1] = '\0';
 
return str;
}
 
char *
ltrim(char *str)
{
char *ptr;
int len;
 
for (ptr = str; *ptr && isspace((int)*ptr); ++ptr);
 
len = strlen(ptr);
memmove(str, ptr, len + 1);
 
return str;
}
 
char *
trim(char *str)
{
char *ptr;
ptr = rtrim(str);
str = ltrim(ptr);
return str;
}
</source>
 
The [[open-source software|open source]] C++ library [[Boost library|Boost]] has several trim variants, including a standard one<ref>http://www.boost.org/doc/html/string_algo/usage.html#id2742817</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,<ref>http://www.boost.org/doc/html/trim.html</ref> 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</ref>
 
<source lang="cpp">
#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>http://www.kernel.org/pub/linux/kernel/v2.6/snapshots/patch-2.6.33-rc1-git1.log</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==
*[[Comparison of programming languages (string functions)]]
 
==External links==
*[httphttps://www.tcl.tk/man/tcl8.4/TclCmd/string.htm#M46 Tcl: string trim]
*[httphttps://blog.stevenlevithan.com/archives/faster-trim-javascript Faster JavaScript Trim] - compares various JavaScript trim implementations
*[http://webwidetutor.com/php/PHP-Change-String-value-behaviour-or-look-?id=8 php string cut and trimming]- php string cut and trimming
 
==Notes==
{{reflist}}
 
[[Category:Articles with example code]]
[[Category:Programming language comparisons]]
[[Category:String (computer science)]]
 
[[fr:Trim (programmation)]]
[[ru:Trim (программирование)]]