Strip whitespace from a string/Top and tail: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(add bqn)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(25 intermediate revisions by 11 users not shown)
Line 18:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V s = " \t \r \n String with spaces \t \r \n "
print(s.ltrim((‘ ’, "\t", "\r", "\n")).len)
print(s.rtrim((‘ ’, "\t", "\r", "\n")).len)
print(s.trim((‘ ’, "\t", "\r", "\n")).len)</langsyntaxhighlight>
 
{{out}}
Line 31:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE SPACE="32"
DEFINE TAB="127"
DEFINE NEWLINE="155"
Line 86:
Strip(src,dst,1,1)
PrintF("Trim leading and trailing whitespaces:""%S""%E%E",dst)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Strip_whitespace_from_a_string_top_and_tail.png Screenshot from Atari 8-bit computer]
Line 106:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
Line 115:
Put_Line ("'" & Trim (str, Right) & "'");
Put_Line ("'" & Trim (str, Both) & "'");
end StripDemo;</langsyntaxhighlight>
{{out}}
<pre>
Line 126:
=== version 1 ===
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># returns "text" with leading non-printing characters removed #
PROC trim leading whitespace = ( STRING text )STRING:
BEGIN
Line 179:
print( ( "trim trailing: """ + trim trailing whitespace( test ) + """", newline ) );
print( ( "trim both: """ + trim whitespace ( test ) + """", newline ) )
)</langsyntaxhighlight>
{{out}}
<pre>
Line 192:
A single procedure that trims leading space, trailing space, or both.
 
<langsyntaxhighlight lang="algol68">#
string_trim
Trim leading and trailing whitespace from string.
Line 220:
print(("string_trim(' foobar '): expected 'foobar'; actual: "
+ string_trim(" foobar "), newline)) FI
)</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
<p>Amazing Hopper! Flavour "Jambo".</p>
<syntaxhighlight lang="Amazing Hopper">
#include <jambo.h>
 
Main
 
Set stack 25
c = "\t\t\n \n Message to triming\t\n \t"
Printnl ("Original Message: [", c,"]")
Set '"\n\n\UL\ENFNatural syntax:\n\n"', then bold off, and underline off
Set '"Right trim: [", c', Do right trim; then set '"]"'
Set '"\nLeft trim: [", c', Do left trim; Set '"]"'
Set '"\nAll trim: [", c', Do trim, now set '"]"' and print with newline
Underline( Bold( "\n\nFormal syntax:\n\n" ))
Printnl ( "Right trim: [", Rtrim(c),\
"]\nLeft trim: [", Ltrim(c),\
"]\nAll trim: [",Trim(c),"]\n" )
End
</syntaxhighlight>
{{out}}
<pre>
Original Message: [
Message to triming
]
 
 
Natural syntax:
 
Right trim: [
Message to triming]
Left trim: [Message to triming
]
All trim: [Message to triming]
 
 
Formal syntax:
 
Right trim: [
Message to triming]
Left trim: [Message to triming
]
All trim: [Message to triming]
 
</pre>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">use framework "Foundation" -- "OS X" Yosemite onwards, for NSRegularExpression
 
-- STRIP WHITESPACE ----------------------------------------------------------
Line 340 ⟶ 396:
|error|:(missing value))'s firstMatchInString:oString options:0 ¬
range:{location:0, |length|:oString's |length|()}) is not missing value
end regexTest</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{"-->Much Ado About Nothing
<--", "-->
Much Ado About Nothing<--", "-->Much Ado About Nothing<--"}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">str: " Hello World "
 
print [pad "strip all:" 15 ">" strip str "<"]
print [pad "strip leading:" 15 ">" strip.start str "<"]
print [pad "strip trailing:" 15 ">" strip.end str "<"]</langsyntaxhighlight>
 
{{out}}
Line 364 ⟶ 420:
=={{header|AutoHotkey}}==
AutoHotkey_L and v2 contain a [http://www.autohotkey.net/~Lexikos/AutoHotkey_L/docs/commands/Trim.htm Trim function]
<langsyntaxhighlight AutoHotkeylang="autohotkey">string := " abc "
MsgBox % clipboard := "<" LTrim(string) ">`n<" RTrim(string) ">`n<" . Trim(string) ">"</langsyntaxhighlight>
{{out}}
<pre><abc >
Line 374 ⟶ 430:
*[:graph:] is a POSIX character class for characters that are both printable and visible. The following strips the entire non-[:graph:] character set. A simplified version for the more common task of removing only spaces and tabs follows it.
 
<langsyntaxhighlight lang="awk">function trimleft(str ,c, out, arr) {
c = split(str, arr, "")
for ( i = match(str, /[[:graph:]]/); i <= c; i++)
Line 402 ⟶ 458:
print "right = |" trimright(str) "|"
print "both = |" trim(str) "|"
}</langsyntaxhighlight>
 
{{out|Output from 26 May 2015}}
Line 422 ⟶ 478:
Simplified for removing [:blank:] (spaces and tabs) or [:space:] (for [ \t\r\n\v\f] ). This method does not work using [:graph:]
 
<langsyntaxhighlight lang="awk">function trim(str) {
gsub(/^[[:blank:]]+/,"", str) # Remove leading
gsub(/[[:blank:]]+$/,"", str) # Remove trailing
gsub(/^[[:blank:]]+|[[:blank:]]+$/, "", str) # Remove both
return str;
}</langsyntaxhighlight>
 
=={{header|BaCon}}==
 
<langsyntaxhighlight lang="qbasic">
'---Remove leading whitespace
PRINT CHOP$(" String with spaces "," ",1)
Line 440 ⟶ 496:
'---Remove both leading and trailing whitespace
PRINT CHOP$(" String with spaces "," ",0)
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic"> mystring$=ltrim(mystring$) ' remove leading whitespace
mystring$=rtrim(mystring$) ' remove trailing whitespace
mystring$=ltrim(rtrim(mystring$)) ' remove both leading and trailing whitespace</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="freebasic">s$ = " \tRosetta Code \v\f\r\n"
 
print ltrim(s$) # remove leading whitespace
print rtrim(s$) # remove trailing whitespace
print trim(s$) # remove both leading and trailing whitespace</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> REM Remove leading whitespace:
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
Line 457 ⟶ 520:
REM Remove both leading and trailing whitespace:
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
WHILE ASC(RIGHT$(A$))<=32 A$ = LEFT$(A$) : ENDWHILE</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 465 ⟶ 528:
Composing the leading and trailing idioms removes whitespace from both sides.
 
<langsyntaxhighlight lang="bqn">ws ← @+⟨9, 10, 11, 12, 13, 32, 133, 160,
5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198,
8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287,
12288⟩
Lead ← (¬·∧`∊⟜ws)⊸/
Trail ← (¬·⌽·∧`·∊⟜ws⌽⌾⌽∊⟜ws)⊸/
 
•Show Lead " fs df"
•Show Trail "fdsf asd "
•Show Lead∘Trail " white space "</langsyntaxhighlight><syntaxhighlight lang="text">"fs df"
"fdsf asd"
"white space"</langsyntaxhighlight>
 
=={{header|Bracmat}}==
Greedy pattern matching is not Bracmat's strongest field. So instead of a pattern that globs all white space characters, we have a pattern that finds the first non-whitespace character. That character, and the remainder of the subject string, constitute a left trimmed string. To do a right trim, we reverse the string, do a left trim and reverse back.
<langsyntaxhighlight lang="bracmat">( ( ltrim
= s
. @( !arg
Line 513 ⟶ 576:
& out$(str$("trim :[" trim$!string "]"))
&
);</langsyntaxhighlight>
Output (Notice the effect of the ancient \a (alarm) and \v (vertical tab)):
<pre>Input:[ Hear
Line 534 ⟶ 597:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) " this is a string "t[
"this is a string "
Line 541 ⟶ 604:
blsq ) " this is a string "tt
"this is a string"
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 589 ⟶ 652:
free(d);
return 0;
}</langsyntaxhighlight>
 
==={{header|Gadget}}===
 
<p>Gadget C-library:
[https://github.com/DanielStuardo/Gadget Gadget C-library in Github]
</p>
<syntaxhighlight lang="c">
#include <gadget/gadget.h>
 
LIB_GADGET_START
 
Main
String r,s,t;
Stack{
Store ( r, Trim_r (Upper(" \n\t este mensaje será modificado " )) )
Store ( s, Trim_l (Reverse(Upper(" \n\t este mensaje será odasrever " ))) )
Store ( t, Trim (Upper(" \n\t este mensaje será modificado " )) )
}Stack_off
Print "Right Trim = [%s]\nLeft Trim = [%s]\nAll Trim = [%s]\n",r,s,t;
 
Free secure r,t, s;
End
</syntaxhighlight>
{{out}}
<pre>
Right Trim = [
ESTE MENSAJE SERÁ MODIFICADO]
Left Trim = [REVERSADO ÁRES EJASNEM ETSE
]
All Trim = [ESTE MENSAJE SERÁ MODIFICADO]
 
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
public class TrimExample
Line 608 ⟶ 704:
return "'" + s + "'";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 617 ⟶ 713:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
Line 631 ⟶ 727:
std::cout << "Trimmed on both sides :" << testphrase << "\n" ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<PRE>The test phrase is : There are unwanted blanks here!
Line 639 ⟶ 735:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(use 'clojure.string)
(triml " my string ")
Line 647 ⟶ 743:
(trim " \t\r\n my string \t\r\n ")
=> "my string"
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
<langsyntaxhighlight lang="cobol">DISPLAY "'" FUNCTION TRIM(str, LEADING) "'"
DISPLAY "'" FUNCTION TRIM(str, TRAILING) "'"
DISPLAY "'" FUNCTION TRIM(str) "'"</langsyntaxhighlight>
 
{{works with|IBM ILE COBOL}}
<langsyntaxhighlight lang="cobol">DISPLAY "'" FUNCTION TRIML(str) "'"
DISPLAY "'" FUNCTION TRIMR(str) "'"
DISPLAY "'" FUNCTION TRIM(str) "'"</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">; Common whitespace characters
(defvar *whitespace* '(#\Space #\Newline #\Tab))
 
Line 696 ⟶ 792:
 
(string-right-trim *unicode-whitespace* unicode-str)
; -> "  foo bar baz"</langsyntaxhighlight>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
def strip_whitepace(s)
puts s.lstrip()
Line 710 ⟶ 806:
# => hello
# => hello
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string;
 
void main() {
Line 720 ⟶ 816:
assert(s.stripRight() == " \t \r \n String with spaces");
assert(s.strip() == "String with spaces");
}</langsyntaxhighlight>
 
=={{header|Delphi}}/{{header|Pascal}}==
<langsyntaxhighlight Delphilang="delphi">program StripWhitespace;
 
{$APPTYPE CONSOLE}
Line 736 ⟶ 832:
Writeln('"' + TrimRight(TEST_STRING) + '"');
Writeln('"' + Trim(TEST_STRING) + '"');
end.</langsyntaxhighlight>
 
=={{header|DWScript}}==
{{Trans|Delphi}}
<langsyntaxhighlight Delphilang="delphi">const TEST_STRING = ' String with spaces ';
 
PrintLn('"' + TEST_STRING + '"');
PrintLn('"' + TrimLeft(TEST_STRING) + '"');
PrintLn('"' + TrimRight(TEST_STRING) + '"');
PrintLn('"' + Trim(TEST_STRING) + '"');</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang=easylang>
func iswhite c$ .
if c$ = " " or c$ = "\t" or c$ = "\n"
return 1
.
.
func$ strip s$ top tail .
a = 1
if top = 1
repeat
c$ = substr s$ a 1
until iswhite c$ = 0
a += 1
.
.
b = len s$
if tail = 1
repeat
c$ = substr s$ b 1
until iswhite c$ = 0
b -= 1
.
.
return substr s$ a (b - a + 1)
.
print strip " Hello world " 1 1 & "."
print strip " Hello world " 0 1 & "."
print strip " Hello world " 1 1 & "."
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define witt
" The limits of my world are the limits of my langage. ")
Line 757 ⟶ 885:
(string->html (string-trim-right witt))
→ " The limits of my world are the limits of my langage."
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">import extensions;
public program()
Line 769 ⟶ 897:
console.printLine("'", toTrim.trimRight(),"'");
console.printLine("'", toTrim.trim(),"'");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 778 ⟶ 906:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">str = "\n \t foo \n\t bar \t \n"
IO.inspect String.strip(str)
IO.inspect String.rstrip(str)
IO.inspect String.lstrip(str)</langsyntaxhighlight>
{{out}}
<pre>
Line 793 ⟶ 921:
As of Emacs 24.4, the subr-x.el library contains string trimming functions:
 
<langsyntaxhighlight Lisplang="lisp">(string-trim-left " left center right ") ;=> "left center right "
(string-trim-right " left center right ") ;=> " left center right"
(string-trim " left center right ") ;=> "left center right"</langsyntaxhighlight>
 
This can be emulated by using regex replacement:
 
<langsyntaxhighlight Lisplang="lisp">(defun string-trim-left (str)
(replace-regexp-in-string "^[ \t\r\n]*" "" str))
 
Line 806 ⟶ 934:
 
(defun string-trim (str)
(string-trim-left (string-trim-right str)))</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
1> string:strip(" Hello World! ", left). %remove leading whitespaces
"Hello World! "
Line 818 ⟶ 946:
3> string:strip(" Hello World! ", both). % remove both leading and trailing whitespace
"Hello World!"
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
Line 828 ⟶ 956:
using escaped hexadecimal , example : \x04 to represent hexadecimal ascii 04 or \u2A7C for 4-digit UTF, or more than two digit ascii characters : \u0127.
 
<langsyntaxhighlight lang="euphoria">include std/console.e
include std/text.e
 
Line 844 ⟶ 972:
end for
any_key()</langsyntaxhighlight>
Output:<pre>
String Trimmed is now: A B C
Line 858 ⟶ 986:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">[<EntryPoint>]
let main args =
printfn "%A" (args.[0].TrimStart())
printfn "%A" (args.[0].TrimEnd())
printfn "%A" (args.[0].Trim())
0</langsyntaxhighlight>
<pre>
>rosetta " a string "
Line 872 ⟶ 1,000:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<langsyntaxhighlight lang="factor">USE: unicode
" test string " [ blank? ] trim ! leading and trailing
" test string " [ blank? ] trim-head ! only leading
" test string " [ blank? ] trim-tail ! only trailing</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 882 ⟶ 1,010:
After the string processing is completed on the stack the program can print or copy back to memory as required.
 
<langsyntaxhighlight lang="forth">: -leading ( addr len -- addr' len' ) \ called "minus-leading"
begin
over c@ bl = \ fetch character at addr, test if blank (space)
Line 888 ⟶ 1,016:
\ cut 1 leading character by incrementing address & decrementing length
1 /string \ "cut-string"
repeat ;</langsyntaxhighlight>
The counterpart function "-trailing" is normally part of a standard forth system,
so by concatenating both we create a "STRIP" function.
<syntaxhighlight lang="text"> : strip ( addr len -- addr' len') -leading -trailing ; </langsyntaxhighlight>
Test at the Forth console
<pre>: mystring s" Trim this string. " ;
Line 908 ⟶ 1,036:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const whitespace = !" \t\n\v\f\r"
Line 931 ⟶ 1,059:
Print "Right trimmed" , "=> Length = "; Len(s2)
Print "Fully trimmed" , "=> Length = "; Len(s3)
Sleep</langsyntaxhighlight>
 
{{out}}
Line 946 ⟶ 1,074:
Right trimmed => Length = 15
Fully trimmed => Length = 12
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1
 
CFCharacterSetRef set, invSet
CFStringRef s, s1, s2, s3
NSUInteger index
CFRange range
 
set = fn CharacterSetWhitespaceAndNewlineSet
invSet = fn CharacterSetInvertedSet( set )
 
text ,,,,, 200
 
s = @" a string "// 5 leading spaces, 8 trailing spaces
print s, len(s)@" chars"
 
// left trim
index = 0
range = fn StringRangeOfCharacterFromSet( s, invSet )
if ( range.location != NSNotFound ) then index = range.location
s1 = fn StringSubstringFromIndex( s, index )
print s1, len(s1)@" chars"
 
// right trim
index = len(s)
range = fn StringRangeOfCharacterFromSetWithOptions( s, invSet, NSBackwardsSearch )
if ( range.location != NSNotFound ) then index = range.location + 1
s2 = fn StringSubstringToIndex( s, index )
print s2, len(s2)@" chars"
 
// trim
s3 = fn StringByTrimmingCharactersInSet( s, set )
print s3, len(s3)@" chars"
 
HandleEvents</syntaxhighlight>
{{out}}
<pre>
a string 21 chars
a string 16 chars
a string 13 chars
a string 8 chars
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=62e56fea0f74819daa3d3a548869fa90 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String = " Hello world! "
 
Line 958 ⟶ 1,129:
Print Trim(sString) & "\t\tString length = " & Len(Trim(sString)) & " - String with both leading and trailing whitespace removed"
 
End</langsyntaxhighlight>
Output:
<pre>
Line 968 ⟶ 1,139:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 989 ⟶ 1,160:
func show(label, str string) {
fmt.Printf("%s: |%s| %v\n", label, str, []rune(str))
}</langsyntaxhighlight>
Example text is shows a leading linefeed and tab, and three trailing spaces. The code uses the Unicode definition of whitespace. Other defintions could be implemented with a custom function given to TrimXFunc.
 
Line 1,004 ⟶ 1,175:
=={{header|Groovy}}==
Solution uses StringUtils class from [http://commons.apache.org/lang/ Apache Commons "Lang" library]:
<langsyntaxhighlight lang="groovy">//Grape setup to get library
@Grab('org.apache.commons:commons-lang3:3.0.1')
import static org.apache.commons.lang3.StringUtils.*
Line 1,025 ⟶ 1,196:
println '============\n\nRight Stripped\n------------'
printTest stripEnd(abc, null)
println '============'</langsyntaxhighlight>
{{out}}
<pre>Unstripped
Line 1,052 ⟶ 1,223:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (isSpace)
import Data.List (dropWhileEnd)
 
Line 1,062 ⟶ 1,233:
 
trim :: String -> String
trim = trimLeft . trimRight</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
This solution takes the phrase "other such characters that have no corresponding graphical representation" quite literallly.
<langsyntaxhighlight Uniconlang="unicon">procedure main()
unp := &cset[1+:32]++' \t'++&cset[127:0] # all 'unprintable' chars
s := " Hello, people of earth! "
Line 1,073 ⟶ 1,244:
write("trailing trim: '",trim(s,unp),"'")
write("full trim: '",reverse(trim(reverse(trim(s,unp)),unp)),"'")
end</langsyntaxhighlight>
{{out|Sample run}}
<pre>->trim
Line 1,084 ⟶ 1,255:
=={{header|J}}==
Note: The <code>quote</code> verb is only used to enclose the resulting string in single quotes so the beginning and end of the new string are visible.
<langsyntaxhighlight lang="j"> require 'strings' NB. the strings library is automatically loaded in versions from J7 on
quote dlb ' String with spaces ' NB. delete leading blanks
'String with spaces '
Line 1,090 ⟶ 1,261:
' String with spaces'
quote dltb ' String with spaces ' NB. delete leading and trailing blanks
'String with spaces'</langsyntaxhighlight>
In addition <code>deb</code> (delete extraneous blanks) will trim both leading and trailing blanks as well as replace consecutive spaces within the string with a single space.
<langsyntaxhighlight lang="j"> quote deb ' String with spaces ' NB. delete extraneous blanks
'String with spaces'</langsyntaxhighlight>
These existing definitions can be easily amended to include whitespace other than spaces if desired.
<langsyntaxhighlight lang="j">whpsc=: ' ',TAB NB. define whitespace as desired
dlws=: }.~ (e.&whpsc i. 0:) NB. delete leading whitespace (spaces and tabs)
dtws=: #~ ([: +./\. -.@:e.&whpsc) NB. delete trailing whitespace
dltws=: #~ ([: (+./\ *. +./\.) -.@:e.&whpsc) NB. delete leading & trailing whitespace
dews=: #~ (+. (1: |. (> </\)))@(-.@:e.&whpsc) NB. delete extraneous whitespace</langsyntaxhighlight>
 
=={{header|Java}}==
Java has the ''trim'' and ''strip'' operations. Both will achieve a similar result.<br />
 
The <code>trim</code> method works on Unicode values under <kbd>0x20</kbd>. Whereas, ''strip'' will remove all Unicode white-space characters.
<syntaxhighlight lang="java">
" abc".stripLeading()
</syntaxhighlight>
<syntaxhighlight lang="java">
"abc ".stripTrailing()
</syntaxhighlight>
<syntaxhighlight lang="java">
" abc ".strip()
</syntaxhighlight>
<syntaxhighlight lang="java">
" abc ".trim()
</syntaxhighlight>
For more control over what characters should be removed, you could implement your own methods.
<syntaxhighlight lang="java">
String removeLeading(String string, char[] characters) {
int index = 0;
for (char characterA : string.toCharArray()) {
for (char characterB : characters) {
if (characterA != characterB)
return string.substring(index);
}
index++;
}
return string;
}
</syntaxhighlight>
<syntaxhighlight lang="java">
String removeTrailing(String string, char[] characters) {
for (int index = string.length() - 1; index >= 0; index--) {
for (char character : characters) {
if (string.charAt(index) != character)
return string.substring(0, index + 1);
}
}
return string;
}
</syntaxhighlight>
<br />
An alternate demonstration<br />
Java offers <code>String.trim</code>. However, this function only strips out ASCII control characters. As such it should generally be avoided for processing text.
 
Line 1,109 ⟶ 1,320:
Left trim and right trim taken from [http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html here].
 
<langsyntaxhighlight lang="java">public class Trims{
public static String ltrim(String s) {
int i = 0;
Line 1,136 ⟶ 1,347:
System.out.printf("[%s]\n", trim(s));
}
}</langsyntaxhighlight>
 
===Supplementary-correct version===
Unicode *happens* to not have any whitespace characters outside of Basic Multilingual Plane (aka, they all fit inside a <code>char</code>). However, this not something you should ''generally'' rely on, and should assume your strings contain characters in the Supplementary Planes. As such, instead of iterating using <code>String.charAt</code>, prefer instead using <code>String.codePointAt</code> and <code>String.codePointBefore</code>, iterating over actual Unicode Code Points:
 
<langsyntaxhighlight lang="java"> public static String ltrim(String s) {
int offset = 0;
while (offset < s.length()) {
Line 1,160 ⟶ 1,371:
return s.substring(0, offset);
}
</syntaxhighlight>
</lang>
 
=={{header|Javascript}}==
{{works with|Node.js}}
{{works with|ECMAScript standard|2015}}
<langsyntaxhighlight lang="javascript">{
let s = " \t String with spaces \t ";
// a future version of ECMAScript will have trimStart(). Some current
Line 1,175 ⟶ 1,386:
console.log("trimmed right: '" + s.replace(/\s+$/,'') + "'");
console.log("trimmed both: '" + s.trim() + "'");
}</langsyntaxhighlight>
{{Output}}
<pre>original: ' String with spaces '
Line 1,186 ⟶ 1,397:
 
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,234 ⟶ 1,445:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,250 ⟶ 1,461:
 
Notice that since jq strings are JSON strings, one must, for example, write "\\s" for the regex '\s'.
<langsyntaxhighlight lang="jq">def lstrip: sub( "^[\\s\\p{Cc}]+"; "" );
 
def rstrip: sub( "[\\s\\p{Cc}]+$"; "" );
 
def strip: lstrip | rstrip;</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">def demo:
"lstrip: \(lstrip)",
"rstrip: \(rstrip)",
Line 1,265 ⟶ 1,476:
"\u0001 \u0002 <- ^A ^B"
) | demo
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -n -f Strip_whitespace_top_tail.jq
"lstrip: String with spaces \t \r \n "
"rstrip: \t \r \n String with spaces"
Line 1,275 ⟶ 1,486:
"lstrip: <- ^A ^B"
"rstrip: \u0001 \u0002 <- ^A ^B"
"strip: <- ^A ^B"</langsyntaxhighlight>
 
=={{header|Jsish}}==
Using echo-mode unitTest lines. Lines starting with semicolon are echoed and captured during test.
 
<langsyntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* Strip whitespace from string, in Jsi */
var str = ' \n \t String with whitespace \t \n ';
Line 1,313 ⟶ 1,524:
str.trim() ==> String with whitespace
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,336 ⟶ 1,547:
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">julia> s = " \t \r \n String with spaces \t \r \n "
" \t \r \n String with spaces \t \r \n "
 
Line 1,346 ⟶ 1,557:
 
julia> strip(s)
"String with spaces"</langsyntaxhighlight>
 
=={{header|K}}==
<syntaxhighlight lang=K>dlb: {((" "<x)?1)_x}
dtb: {(-(|" "<x)?1)_x}
 
dlb " this is a test "
"this is a test "
dtb " this is a test "
" this is a test"
dtb dlb " this is a test "
"this is a test"
dtb dlb "this is a test"
"this is a test"</syntaxhighlight>
 
tested with ngn/k
 
=={{header|Kotlin}}==
Line 1,353 ⟶ 1,579:
Kotlin’s <code>trim</code> family of functions also optionally accept a predicate, which can further customize the stripping behavior, if Unicode whitespace is not what is desired.
 
<langsyntaxhighlight lang="kotlin">fun main(args: Array<String>) {
val s = " \tRosetta Code \r \u2009 \n"
println("Untrimmed => [$s]")
Line 1,359 ⟶ 1,585:
println("Right Trimmed => [${s.trimEnd()}]")
println("Fully Trimmed => [${s.trim()}]")
}</langsyntaxhighlight>
 
{{out}}
Line 1,372 ⟶ 1,598:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 1,414 ⟶ 1,640:
printf ">%s< (Strip trailing (%d chars))\n" "${sstr}" $(( ${#str}-${#sstr} ))
sstr=$(_striphead "$(_striptail "${str}")")
printf ">%s< (Strip both (%d chars))\n" "${sstr}" $(( ${#str}-${#sstr} ))</langsyntaxhighlight>
{{out}}<pre>> This is a test. < (Unstripped 19 chars)
>This is a test. < (Strip leading (1 chars))
Line 1,421 ⟶ 1,647:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
initial string : {def string ___String with "_" displaying space_____}
-> string ___String with "_" displaying space_____
Line 1,433 ⟶ 1,659:
trimBoth : {S.replace _+$ by in {S.replace ^_+ by in {string}}}
-> String with "_" displaying space
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
Line 1,439 ⟶ 1,665:
 
The '>' and '<' strings have been included in this example to demonstrate the whitespace trim.
<langsyntaxhighlight Lassolang="lasso">// String with leading whitespace removed
'>' + (' \t Hello')->trim& + '<'
 
Line 1,446 ⟶ 1,672:
 
// String with both leading and trailing whitespace removed
'>' + (' \t Hello \t ')->trim& + '<'</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">a$=" This is a test "
 
'LB TRIM$ removes characters with codes 0..31 as well as a space(code 32)
Line 1,476 ⟶ 1,702:
end function
</syntaxhighlight>
</lang>
 
=={{header|Logtalk}}==
Using atoms for representing strings and assuming an ASCII text encoding:
<langsyntaxhighlight lang="logtalk">
:- object(whitespace).
 
Line 1,510 ⟶ 1,736:
 
:- end_object.
</syntaxhighlight>
</lang>
Sample output:
<langsyntaxhighlight lang="text">
| ?- whitespace::trim('\n\t Rosetta Code \t\n', TrimLeft, TrimRight, TrimBoth).
TrimLeft = 'Rosetta Code \t\n',
Line 1,518 ⟶ 1,744:
TrimBoth = 'Rosetta Code'
yes
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">str = " \t \r \n String with spaces \t \r \n "
 
print( string.format( "Leading whitespace removed: %s", str:match( "^%s*(.+)" ) ) )
print( string.format( "Trailing whitespace removed: %s", str:match( "(.-)%s*$" ) ) )
print( string.format( "Leading and trailing whitespace removed: %s", str:match( "^%s*(.-)%s*$" ) ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
filter$=chr$(0)
Line 1,557 ⟶ 1,783:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,571 ⟶ 1,797:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">str := " \t \r \n String with spaces \t \r \n ";
 
with(StringTools):
Line 1,577 ⟶ 1,803:
TrimLeft(str);
TrimRight(str);
Trim(str);</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">StringTrim[" \n\t string with spaces \n \t "]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight lang="matlab">% remove trailing whitespaces
str = str(1:find(~isspace(str),1,'last'));
% remove leading whitespaces
Line 1,593 ⟶ 1,819:
 
% a built-in function, removes leading and trailing whitespaces
str = strtrim(str);</langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module top_and_tail.
:- interface.
 
Line 1,609 ⟶ 1,835:
io.format("leading ws removed: %s\n", [s(lstrip(TestPhrase))], !IO),
io.format("trailing ws removed: %s\n", [s(rstrip(TestPhrase))], !IO),
io.format("both removed: %s\b", [s(strip(TestPhrase))], !IO).</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">def str = "\t\n\t A string with\nwhitespace\n\n\t ";
WriteLine(str.TrimStart());
WriteLine(str.TrimEnd());
WriteLine(str.Trim()); // both ends at once, of course, internal whitespace is preserved in all 3</langsyntaxhighlight>
 
=={{header|NetRexx}}==
NetRexx provides a <tt>strip()</tt> method which can be used to remove all of a single character from the head and/or tail of a string. To remove ''all'' whitespace characters from a string requires a little more work:
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,708 ⟶ 1,934:
 
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre style="height: 25ex; overflow:scroll;">
Line 1,757 ⟶ 1,983:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(setq str " this is a string ")
 
;; trim leading blanks
Line 1,766 ⟶ 1,992:
 
;; trim both leading and trailing blanks
(trim str)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
let s = "\t \v \r String with spaces \n \t \f"
Line 1,779 ⟶ 2,005:
echo("*** Stripped of leading and trailing spaces ***")
echo "“", s.strip(), "”"
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,798 ⟶ 2,024:
=={{header|Oberon-2}}==
Oxford Oberon-2
<langsyntaxhighlight lang="oberon2">
MODULE Trim;
IMPORT Out,Strings,SYSTEM;
Line 1,857 ⟶ 2,083:
Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);LTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln;
END Trim.
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,873 ⟶ 2,099:
{{works with|Cocoa}}
{{works with|GNUstep}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSString (RCExt)
Line 1,925 ⟶ 2,151:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let left_pos s len =
let rec aux i =
if i >= len then None
Line 1,963 ⟶ 2,189:
match right_pos s len with
| Some i -> String.sub s 0 (i + 1)
| None -> ""</langsyntaxhighlight>
we put the previous code in a file called "trim.ml", and then we test these functions in the toplevel:
<pre>$ ocaml
Line 1,984 ⟶ 2,210:
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">DEF VAR cc AS CHAR INIT " string with spaces ".
 
MESSAGE
Line 1,990 ⟶ 2,216:
"|" + RIGHT-TRIM( cc ) + "|" SKIP
"|" + TRIM( cc ) + "|"
VIEW-AS ALERT-BOX.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,005 ⟶ 2,231:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub ltrim { shift =~ s/^\s+//r }
sub rtrim { shift =~ s/\s+$//r }
sub trim { ltrim rtrim shift }
Line 2,014 ⟶ 2,240:
print "'", trim($p), "'\n";
print "'", ltrim($p), "'\n";
print "'", rtrim($p), "'\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">constantwith</span> <span style="color: #000000008080;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"\ttest\n"javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"\t test \n"</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">trim_head</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">trim_tail</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
"\ttestt test \n"
"testtest \n"
"\ttestt test"
"test"
</pre>
Line 2,035 ⟶ 2,262:
=={{header|PHP}}==
There is a built-in function that already does this.
<langsyntaxhighlight PHPlang="php"><?php
 
/**
Line 2,045 ⟶ 2,272:
echo '^'.ltrim($string).'$'.PHP_EOL;
echo '^'.rtrim($string).'$'.PHP_EOL;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,052 ⟶ 2,279:
^ this is a string$
</pre>
 
=={{header|Picat}}==
Using the built-in functions <code>lstrip/1</code>, <code>rstrip/1</code>, <code>strip/1</code>, and <code>strip/2</code>.
<syntaxhighlight lang="picat">import util.
 
go =>
S = " Jabberwocky ",
println("<" ++ S ++ ">"),
 
println("<" ++ lstrip(S) ++ ">"),
println("<" ++ rstrip(S) ++ ">"),
println("<" ++ strip(S) ++ ">"),
println("<" ++ strip("\t\r\bTwas brillig, and the slithy toves\r \t\v"," \b\v\t\r\v") ++ ">"),
nl.</syntaxhighlight>
 
{{out}}
<pre>< Jabberwocky >
<Jabberwocky >
< Jabberwocky>
<Jabberwocky>
<Twas brillig, and the slithy toves></pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de trimLeft (Str)
(pack (flip (trim (flip (chop Str))))) )
 
Line 2,061 ⟶ 2,309:
 
(de trimBoth (Str)
(pack (clip (chop Str))) )</langsyntaxhighlight>
Test:
<pre>: (trimLeft " ^G ^I trimmed left ^L ")
Line 2,073 ⟶ 2,321:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">put ( trim(text, ' ', '') ); /* trims leading blanks. */
put ( trim(text, '', ' ') ); /* trims trailing blanks. */
put ( trim(text) ); /* trims leading and trailing */
/* blanks. */</langsyntaxhighlight>
To remove any white-space character(s) in a portable way:-
<langsyntaxhighlight lang="pli">declare whitespace character(33) value
((substr(collate(), 1, 32) || ' '));
put ( trim(text, whitespace) ); /* trims leading white space. */
Line 2,084 ⟶ 2,332:
put ( trim(text, whitespace, whitespace) );
/* trims leading and trailing */
/* white space. */</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$var = " Hello World "
$var.TrimStart() # String with leading whitespace removed
$var.TrimEnd() # String with trailing whitespace removed
$var.Trim() # String with both leading and trailing whitespace removed
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,102 ⟶ 2,350:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">strip :-
In = " There are unwanted blanks here! ",
strip_left(In, OutLeft),
Line 2,131 ⟶ 2,379:
 
strip_action(X) --> X.
</syntaxhighlight>
</lang>
Output :
<pre> ?- strip.
Line 2,149 ⟶ 2,397:
{{works with|SWI-Prolog|7}}
 
<langsyntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,chars) .
 
Line 2,236 ⟶ 2,484:
\+ [_] % .i.e. at end-of-string .
.
</syntaxhighlight>
</lang>
 
 
Line 2,256 ⟶ 2,504:
=={{header|PureBasic}}==
Note, if only spaces need to be removed, PureBasic provides commands that do this: <tt>LTrim()</tt>, <tt>RTrim()</tt>, and <tt>Trim()</tt>. To handle a larger selection of whitespace the following functions meet the task.
<langsyntaxhighlight PureBasiclang="purebasic">;define the whitespace as desired
#whitespace$ = " " + Chr($9) + Chr($A) + Chr($B) + Chr($C) + Chr($D) + Chr($1C) + Chr($1D) + Chr($1E) + Chr($1F)
 
Line 2,292 ⟶ 2,540:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>"Top "
Line 2,299 ⟶ 2,547:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> s = ' \t \r \n String with spaces \t \r \n '
>>> s
' \t \r \n String with spaces \t \r \n '
Line 2,308 ⟶ 2,556:
>>> s.strip()
'String with spaces'
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
As a dialogue in the Quackery shell.
 
<langsyntaxhighlight Quackerylang="quackery">/O> [ reverse trim reverse ] is trim-trailing ( $ --> $ )
... [ trim trim-trailing ] is trim-both-ends ( $ --> $ )
... $ ' a quick quack ' echo$ say "!" cr
Line 2,325 ⟶ 2,573:
a quick quack!
 
Stack empty.</langsyntaxhighlight>
 
=={{header|R}}==
 
<langsyntaxhighlight Rlang="r">s <- " Ars Longa "
 
trimws(s)
Line 2,338 ⟶ 2,586:
 
trimws(s, "right")
[1] " Ars Longa"</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,358 ⟶ 2,606:
;; can also normalize spaces:
(string-normalize-spaces (string-trim str)) ; -> "foo bar"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2020.08.1}}
<syntaxhighlight lang="raku" perl6line>my $s = "\r\n \t\x2029 Good Stuff \x202F\n";
say $s.trim;
say $s.trim.raku;
say $s.trim-leading.raku;
say $s.trim-trailing.raku;</langsyntaxhighlight>
 
{{Output}}
Line 2,378 ⟶ 2,626:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">>> trim/head " remove leading white space "
== "remove leading white space "
>> trim/tail " remove trailing white space "
== " remove trailing white space"
>> trim " remove both white spaces "
== "remove both white spaces"</langsyntaxhighlight>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">'__this_is_a_test___ s:trim-left
'__this_is_a_test___ s:trim-right
'__this_is_a_test___ s:trim</langsyntaxhighlight>
 
=={{header|REXX}}==
 
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates how to strip leading and/or trailing spaces (blanks). */
yyy=" this is a string that has leading/embedded/trailing blanks, fur shure. "
say 'YYY──►'yyy"◄──" /*display the original string + fence. */
Line 2,420 ⟶ 2,668:
noX=space(yyy) /* including white space between words.*/
say 'nox──►'noX"◄──" /*display the string with a title+fence*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output'''
<pre>
Line 2,431 ⟶ 2,679:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 01.1.2012 Walter Pachl taking care of all non-printable chars
**********************************************************************/
Line 2,455 ⟶ 2,703:
Say 'sa>'sa'<'<' /* between words */
s0=space(sa,0) /* remove all whitespace */
Say 's0>'s0'<'</langsyntaxhighlight>
Output:
<pre>
Line 2,468 ⟶ 2,716:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = " Welcome to the Ring Programming Language "
see aList + nl
see trim(aList) + nl
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
Recursivity provides short code.
'''IF''' DUP 1 1 SUB " " == '''THEN'''
2 OVER SIZE SUB '''TRIM END'''
'''IF''' DUP DUP SIZE DUP SUB " " == '''THEN'''
1 OVER SIZE 1 - SUB '''TRIM END'''
≫ ‘'''TRIM'''’ STO
 
" What if true luxury was space? " '''TRIM'''
{{out}}
<pre>
1: "What if true luxury was space?"
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">s = " \t\v\r\n\ffoo bar \t\v\r\n\f"
p s
p s.lstrip # remove leading whitespaces
p s.rstrip # remove trailing whitespaces
p s.strip # remove both leading and trailing whitespace
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,490 ⟶ 2,753:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">string$ = " abcdefg "
 
print " Top:";trim$(string$+"|") ' top left trim
print "Bottom:";trim$("|"+string$) ' bottom right trim
print " Both:";trim$(string$) ' both left and right
end</langsyntaxhighlight>
<pre> Top:abcdefg
Bottom: abcdefg
Line 2,501 ⟶ 2,764:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let spaces = " \t\n\x0B\x0C\r \u{A0} \u{2000}\u{3000}";
let string_with_spaces = spaces.to_owned() + "String without spaces" + spaces;
Line 2,508 ⟶ 2,771:
assert_eq!(string_with_spaces.trim_left(), "String without spaces".to_owned() + spaces);
assert_eq!(string_with_spaces.trim_right(), spaces.to_owned() + "String without spaces");
}</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
ltrim(s :STR) :STR is
i ::= 0;
Line 2,547 ⟶ 2,810:
#OUT + trim(p).pretty + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def trimLeft(str: String) = str dropWhile(_.isWhitespace)
 
def trimRight(str: String) = str take (str.lastIndexWhere(!_.isWhitespace) + 1)
Line 2,565 ⟶ 2,828:
println("trimRight2: |" + trimRight2(str) + "|")
println("trim : |" + trim(str) + "|")
}</langsyntaxhighlight>
{{out}}
<pre>original : | � String with spaces
Line 2,578 ⟶ 2,841:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,587 ⟶ 2,850:
writeln(rtrim(testStri));
writeln(trim(testStri));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var s = " \t\v\r\n\ffoo bar \t\v\r\n\f";
say s.strip_beg.dump; # remove leading whitespaces
say s.strip_end.dump; # remove trailing whitespaces
say s.strip.dump; # remove both leading and trailing whitespace</langsyntaxhighlight>
{{out}}
<pre>
Line 2,603 ⟶ 2,866:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">String extend
[
ltrim [
Line 2,622 ⟶ 2,885:
('"%1"' % {a ltrim}) displayNl.
('"%1"' % {a rtrim}) displayNl.
('"%1"' % {a trim}) displayNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4"> s1 = s2 = " Hello, people of earth! "
s2 = CHAR(3) s2 CHAR(134)
&ALPHABET TAB(33) . prechars
Line 2,643 ⟶ 2,906:
s2 POS(0) SPAN(stripchars) =
OUTPUT = "Full trim: >" s2 "<"
END</langsyntaxhighlight>
{{out}}
<pre>
Line 2,654 ⟶ 2,917:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">local
open Substring
in
Line 2,660 ⟶ 2,923:
and trimRight = string o dropr Char.isSpace o full
and trim = string o dropl Char.isSpace o dropr Char.isSpace o full
end</langsyntaxhighlight>
 
=={{header|Stata}}==
See '''[https://www.stata.com/help.cgi?mf_strtrim strtrim]''' in Stata help. Use the equivalent '''[https://www.stata.com/help.cgi?mf_ustrtrim ustrtrim]''' functions with Unicode strings.
 
<langsyntaxhighlight lang="stata">s = " ars longa "
"("+strtrim(s)+")"
(ars longa)
Line 2,676 ⟶ 2,939:
 
"("+stritrim(s)+")"
( ars longa )</langsyntaxhighlight>
 
=={{header|Tcl}}==
Whitespace stripping is done with <code>string trim</code> and related commands:
<langsyntaxhighlight lang="tcl">set str " hello world "
puts "original: >$str<"
puts "trimmed head: >[string trimleft $str]<"
puts "trimmed tail: >[string trimright $str]<"
puts "trimmed both: >[string trim $str]<"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,694 ⟶ 2,957:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti-83b">
PROGRAM:WHITESPC
Input Str1
Line 2,722 ⟶ 2,985:
Lbl F
Disp "'"+Str1+"'"
</syntaxhighlight>
</lang>
 
=={{header|TorqueScript}}==
Line 2,743 ⟶ 3,006:
" yep"
"yep"
 
=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">LET s$ = " \tRosetta Code \v\f\r\n"
 
PRINT ltrim$(s$) ! remove leading whitespace
PRINT rtrim$(s$) ! remove trailing whitespace
PRINT trim$(s$) ! remove both leading and trailing whitespace
END</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
str= " sentence w/whitespace before and after "
trimmedtop=EXTRACT (str,":<|<> :"|,0)
Line 2,753 ⟶ 3,024:
PRINT "trimmed on top <|",trimmedtop,">|"
PRINT "trimmed on tail <|", trimmedtail,">|"
PRINT "trimmed on both <|", trimmedboth,">|"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,766 ⟶ 3,037:
===Pattern Matching Language Exercise===
Here, no builtin functions are used, just text pattern matching logic. Two functions are written, conforming to the proper filter convention, and then employed as filters.
<langsyntaxhighlight lang="txr">@(define trim_left (in out))
@ (next :list in)
@/[ \t]*/@out
Line 2,785 ⟶ 3,056:
trim_right: [@{line_of_input :filter (:fun trim_right)}]
trim_both: [@{line_of_input :filter ((:fun trim_left) (:fun trim_right))}]
@(end)</langsyntaxhighlight>
{{out}}
<pre>$ echo "" | txr trim.txr -
Line 2,812 ⟶ 3,083:
Trimming whitespace from both ends is a builtin:
 
<langsyntaxhighlight lang="sh">$ txr -p '(trim-str " a b ")'
"a b"</langsyntaxhighlight>
 
An unnecessarily cryptic, though educational, left trim:
 
<langsyntaxhighlight lang="sh">$ txr -p '[(do progn (del [@1 0..(match-regex @1 #/\s*/)]) @1) " a b "]'
"a b "</langsyntaxhighlight>
 
Explanation: the basic structure is <code>[function " a b "]</code> where the function is an anonymous lambda generated using the <code>do</code> operator. The function is applied to the string <code>" a b "</code>.
Line 2,828 ⟶ 3,099:
Lastly, a pedestrian right trim:
 
<langsyntaxhighlight lang="txrlisp">(defun trim-right (str)
(for ()
((and (> (length str) 0) (chr-isspace [str -1])) str)
Line 2,835 ⟶ 3,106:
(format t "{~a}\n" (trim-right " "))
(format t "{~a}\n" (trim-right "a "))
(format t "{~a}\n" (trim-right ""))</langsyntaxhighlight>
 
Output:
Line 2,845 ⟶ 3,116:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
 
white = ==` !| not @iNC %sI
Line 2,854 ⟶ 3,125:
#cast %sgUL
 
main = <.trim_left,trim_right,trim_both> ' string with spaces '</langsyntaxhighlight>
* The <code>white</code> predicate tests an argument for whiteness by either comparing it to a literal space character or testing whether the singleton list containing it is of a string (<code>%s</code>) type.
* The <code>-~</code> postfix operator takes a predicate to a function that takes a string to a pair of strings whose concatenation is the original string and whose left side is the maximal prefix of the original string whose members satisfy the predicate.
Line 2,868 ⟶ 3,139:
=={{header|Vala}}==
===Strip Leading White Space===
<langsyntaxhighlight lang="vala">string s = " word ";
string s_chug = s.chug();</langsyntaxhighlight>
===Strip Trailing White Space===
<langsyntaxhighlight lang="vala">string s = " word ";
string s_chomp = s.chomp();</langsyntaxhighlight>
===Strip Leading & Trailing White Space===
<langsyntaxhighlight lang="vala">string s = " word ";
string s_strip = s.strip();</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Sub test()
'LTrim trims leading spaces
'RTrim trims tailing spaces
Line 2,888 ⟶ 3,159:
Debug.Print """" & WorksheetFunction.trim(s) & """"
'these functions do not remove tabs or newlines
End Sub</langsyntaxhighlight>{{out}}
<pre>" trim "
"trim "
Line 2,896 ⟶ 3,167:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function LeftTrim(s)
Set regex = New RegExp
Line 2,925 ⟶ 3,196:
WScript.StdOut.WriteLine RightTrim("RosettaCode ")
WScript.StdOut.WriteLine LeftTrim(RightTrim(" RosettaCode "))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,936 ⟶ 3,207:
=={{header|Wren}}==
In Wren 'whitespace' is defined as: space, tab, carriage return, and line feed characters. To trim off other non-printing characters such as form feed and vertical tab, you need to do a little more work.
<langsyntaxhighlight ecmascriptlang="wren">var a = " \t\r\nString with leading whitespace removed"
var b = "String with trailing whitespace removed \t\r\n"
var c = " \t\r\nString with both leading and trailing whitespace removed \t\r\n"
Line 2,943 ⟶ 3,214:
System.print("'%(b.trimEnd())'")
System.print("'%(c.trim())'")
System.print("'%(d.trimStart(" \t\r\n\f\v"))'") // similar overloads of trimEnd and trim exist</langsyntaxhighlight>
 
{{out}}
Line 2,952 ⟶ 3,223:
'String with leading whitespace, form feed and vertical tab characters removed'
</pre>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "progname"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
s$ = " \tRosetta Code \v\f\r\n"
 
PRINT LTRIM$(s$) ' remove leading whitespace
PRINT RTRIM$(s$) ' remove trailing whitespace
PRINT TRIM$(s$) ' remove both leading and trailing whitespace
 
END FUNCTION
END PROGRAM</syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, Text=12;
string 0; \use zero-terminated string convention
 
Line 2,990 ⟶ 3,278:
Text(0, StripTrail(String)); ChOut(0, ^!); CrLf(0);
Text(0, StripTrail(StripLead(String))); ChOut(0, ^!); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 3,000 ⟶ 3,288:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">s$ = "\t test \n"
 
print "--",ltrim$(s$),"--"
print "--",rtrim$(s$),"--"
print "--",trim$(s$),"--"</langsyntaxhighlight>
 
=={{header|zkl}}==
Remove white space from both end of string:
<langsyntaxhighlight lang="zkl">"\t\n hoho\n\t\ ".strip() //-->"hoho"</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn removeLeadingWS(s){ n:=0;
try{ while(s[n].isSpace()){ n+=1 } }catch{""}fallthrough{ s[n,*] }
}
removeLeadingWS("\t\n hoho\n\t\ ") //-->"hoho\n\t "
removeLeadingWS("") //-->""</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn removeTrailingWS(s){ n:=-1;
try{ while(s[n].isSpace()){ n-=1 } s[0,n+1] }catch{""}
}
removeTrailingWS("\t\n hoho\n\t\ ") //-->"\t\n hoho"
removeTrailingWS("\t\n \n\t\ ") //-->""</langsyntaxhighlight>
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: trim_left
input: ' abcd'
Line 3,033 ⟶ 3,321:
input: ' abcd '
output: 'abcd'
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
9,476

edits