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

m
→‎{{header|Wren}}: Changed to Wren S/H
(added Arturo)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(39 intermediate revisions by 20 users not shown)
Line 16:
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
<syntaxhighlight 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)</syntaxhighlight>
 
{{out}}
<pre>
29
25
18
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE SPACE="32"
DEFINE TAB="127"
DEFINE NEWLINE="155"
 
BYTE FUNC IsWhitespace(CHAR c)
IF c=SPACE OR c=TAB OR c=NEWLINE THEN
RETURN (1)
FI
RETURN (0)
 
PROC Strip(CHAR ARRAY src,dst BYTE head,tail)
BYTE i,first,last
 
first=1
last=src(0)
 
IF head THEN
WHILE first<=last
DO
IF IsWhitespace(src(first))=0 THEN
EXIT
FI
first==+1
OD
FI
 
IF tail THEN
WHILE last>=first
DO
IF IsWhitespace(src(last))=0 THEN
EXIT
FI
last==-1
OD
FI
 
IF first>last THEN
dst(0)=0
ELSE
SCopyS(dst,src,first,last)
FI
RETURN
 
PROC Main()
CHAR ARRAY src=" Action! ",dst(20)
 
src(2)=NEWLINE src(13)=TAB
 
PrintF("Original string:%E""%S""%E%E",src)
Strip(src,dst,1,0)
PrintF("Trim leading whitespaces:%E""%S""%E%E",dst)
Strip(src,dst,0,1)
PrintF("Trim trailing whitespaces:%E""%S""%E%E",dst)
Strip(src,dst,1,1)
PrintF("Trim leading and trailing whitespaces:""%S""%E%E",dst)
RETURN</syntaxhighlight>
{{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]
<pre>
Original string:
"
Action! "
 
Trim leading whitespaces:
"Action! "
 
Trim trailing whitespaces:
"
Action!"
 
Trim leading and trailing whitespaces:
"Action!"
</pre>
 
=={{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 27 ⟶ 115:
Put_Line ("'" & Trim (str, Right) & "'");
Put_Line ("'" & Trim (str, Both) & "'");
end StripDemo;</langsyntaxhighlight>
{{out}}
<pre>
Line 38 ⟶ 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 91 ⟶ 179:
print( ( "trim trailing: """ + trim trailing whitespace( test ) + """", newline ) );
print( ( "trim both: """ + trim whitespace ( test ) + """", newline ) )
)</langsyntaxhighlight>
{{out}}
<pre>
Line 104 ⟶ 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 132 ⟶ 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 252 ⟶ 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 276 ⟶ 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 286 ⟶ 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 314 ⟶ 458:
print "right = |" trimright(str) "|"
print "both = |" trim(str) "|"
}</langsyntaxhighlight>
 
{{out|Output from 26 May 2015}}
Line 334 ⟶ 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 352 ⟶ 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 369 ⟶ 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}}==
 
The following program uses an AND-scan (a well known idiom for leading characters) to find the leading whitespace. The whitespace characters are then filtered out from those locations.
 
Composing the leading and trailing idioms removes whitespace from both sides.
 
<syntaxhighlight 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)⊸/
 
•Show Lead " fs df"
•Show Trail "fdsf asd "
•Show Lead∘Trail " white space "</syntaxhighlight><syntaxhighlight lang="text">"fs df"
"fdsf asd"
"white space"</syntaxhighlight>
 
=={{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 406 ⟶ 576:
& out$(str$("trim :[" trim$!string "]"))
&
);</langsyntaxhighlight>
Output (Notice the effect of the ancient \a (alarm) and \v (vertical tab)):
<pre>Input:[ Hear
Line 427 ⟶ 597:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) " this is a string "t[
"this is a string "
Line 434 ⟶ 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 482 ⟶ 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 501 ⟶ 704:
return "'" + s + "'";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 510 ⟶ 713:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
Line 524 ⟶ 727:
std::cout << "Trimmed on both sides :" << testphrase << "\n" ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<PRE>The test phrase is : There are unwanted blanks here!
Line 532 ⟶ 735:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(use 'clojure.string)
(triml " my string ")
Line 540 ⟶ 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 589 ⟶ 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 603 ⟶ 806:
# => hello
# => hello
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string;
 
void main() {
Line 613 ⟶ 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 629 ⟶ 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 650 ⟶ 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 662 ⟶ 897:
console.printLine("'", toTrim.trimRight(),"'");
console.printLine("'", toTrim.trim(),"'");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 671 ⟶ 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 683 ⟶ 918:
 
=={{header|Emacs Lisp}}==
===trim left===
<lang Emacs Lisp>
(defun trim-l (str)
(replace-regexp-in-string "^ +" "" str) )
 
As of Emacs 24.4, the subr-x.el library contains string trimming functions:
(setq str " left between right ")
(insert (trim-l str) )
</lang>
<b>Output:</b>
<pre>
left between right
</pre>
 
<syntaxhighlight lang="lisp">(string-trim-left " left center right ") ;=> "left center right "
===trim right===
(string-trim-right " left center right ") ;=> " left center right"
<lang Emacs Lisp>
(string-trim " left center right ") ;=> "left center right"</syntaxhighlight>
(defun trim-r (str)
(replace-regexp-in-string " +$" "" str) )
 
This can be emulated by using regex replacement:
(setq str " left between right ")
(insert (trim-r str) )
</lang>
<b>Output:</b>
<pre>
left between right
</pre>
===trim version 1===
<lang Emacs Lisp>
(defun trim (str)
(trim-l (trim-r str) ))
 
<syntaxhighlight lang="lisp">(defun string-trim-left (str)
(setq str " left between right ")
(replace-regexp-in-string "^[ \t\r\n]*" "" str))
(insert (trim str) )
</lang>
<b>Output:</b>
<pre>
left between right
</pre>
===trim version 2===
<lang Emacs Lisp>
(defun trim (str)
(mapconcat 'identity (split-string str) " ") )
 
(defun string-trim-right (str)
(setq str " left between right ")
(replace-regexp-in-string "[ \t\r\n]*$" "" str))
(insert (trim str) )
 
</lang>
(defun string-trim (str)
<b>Output:</b>
(string-trim-left (string-trim-right str)))</syntaxhighlight>
<pre>
left between right
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
1> string:strip(" Hello World! ", left). %remove leading whitespaces
"Hello World! "
Line 744 ⟶ 946:
3> string:strip(" Hello World! ", both). % remove both leading and trailing whitespace
"Hello World!"
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
Line 754 ⟶ 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 770 ⟶ 972:
end for
any_key()</langsyntaxhighlight>
Output:<pre>
String Trimmed is now: A B C
Line 784 ⟶ 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 798 ⟶ 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 808 ⟶ 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 814 ⟶ 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 834 ⟶ 1,036:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const whitespace = !" \t\n\v\f\r"
Line 857 ⟶ 1,059:
Print "Right trimmed" , "=> Length = "; Len(s2)
Print "Fully trimmed" , "=> Length = "; Len(s3)
Sleep</langsyntaxhighlight>
 
{{out}}
Line 872 ⟶ 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 884 ⟶ 1,129:
Print Trim(sString) & "\t\tString length = " & Len(Trim(sString)) & " - String with both leading and trailing whitespace removed"
 
End</langsyntaxhighlight>
Output:
<pre>
Line 894 ⟶ 1,139:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 915 ⟶ 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 930 ⟶ 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 951 ⟶ 1,196:
println '============\n\nRight Stripped\n------------'
printTest stripEnd(abc, null)
println '============'</langsyntaxhighlight>
{{out}}
<pre>Unstripped
Line 978 ⟶ 1,223:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (isSpace)
import Data.List (dropWhileEnd)
 
Line 988 ⟶ 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 999 ⟶ 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,010 ⟶ 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,016 ⟶ 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.
 
Rather, the function <code>Character.isWhitespace</code> should be used to strip out any Unicode whitespaces. Note that the Java implementation slightly deviates from the strict Unicode definition: For example, non-breaking spaces are not considered whitespace by Java. This is fine for stripping leading/trailing whitespaces, as a non-breaking space generally should not appear there, but is something to keep in mind.
 
Left trim and right trim taken from [http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html here].
<code>Character.isWhitespace()</code> returns true if the character given is one of the following [[Unicode]] characters: '\u00A0', '\u2007', '\u202F', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u001C', '\u001D', '\u001E', or '\u001F'.
<lang java>
public class Trims{
public static String ltrim(String s){
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))){
i++;
}
return s.substring(i);
}
 
<syntaxhighlight lang="java">public class Trims{
public static String rtrim(String s){
public static intString i =ltrim(String s.length() - 1;{
int i = 0;
while (i > 0 && Character.isWhitespace(s.charAt(i))){
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i--;
} i++;
return s.substring(0, i + 1);}
return s.substring(i);
}
}
 
public static voidString mainrtrim(String[] argss) {
String s =int "i \t= \r \n String with spaces \t \r \ns.length() - "1;
while (i > 0 && Character.isWhitespace(s.charAt(i))) {
System.out.println(ltrim(s));
i--;
System.out.println(rtrim(s));
}
System.out.println(s.trim()); //trims both ends
return s.substring(0, i + 1);
}
}
}</lang>
 
public static String trim(String s) {
return rtrim(ltrim(s));
}
 
public static void main(String[] args) {
String s = " \t \r \n String with spaces \u2009 \t \r \n ";
System.out.printf("[%s]\n", ltrim(s));
System.out.printf("[%s]\n", rtrim(s));
System.out.printf("[%s]\n", trim(s));
}
}</syntaxhighlight>
 
===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:
 
<syntaxhighlight lang="java"> public static String ltrim(String s) {
int offset = 0;
while (offset < s.length()) {
int codePoint = s.codePointAt(offset);
if (!Character.isWhitespace(codePoint)) break;
offset += Character.charCount(codePoint);
}
return s.substring(offset);
}
 
public static String rtrim(String s) {
int offset = s.length();
while (offset > 0) {
int codePoint = s.codePointBefore(offset);
if (!Character.isWhitespace(codePoint)) break;
offset -= Character.charCount(codePoint);
}
return s.substring(0, offset);
}
</syntaxhighlight>
 
=={{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,069 ⟶ 1,386:
console.log("trimmed right: '" + s.replace(/\s+$/,'') + "'");
console.log("trimmed both: '" + s.trim() + "'");
}</langsyntaxhighlight>
{{Output}}
<pre>original: ' String with spaces '
Line 1,080 ⟶ 1,397:
 
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,128 ⟶ 1,445:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,144 ⟶ 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,159 ⟶ 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,169 ⟶ 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,207 ⟶ 1,524:
str.trim() ==> String with whitespace
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,230 ⟶ 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,240 ⟶ 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}}==
It is worth pointing out that Kotlin, unlike Java, has <code>String.trimStart</code> and <code>String.trimEnd</code>. More importantly though, Kotlin’s <code>String.trim</code> actually trims whitespace as defined by Unicode, whereas Java’s just strips Unicode control characters.
<lang scala>// version 1.0.6
 
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.
fun main(args: Array<String>) {
 
val s = " \tRosetta Code \r\n"
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
println("Untrimmed => $s")
val s = " \tRosetta Code \r \u2009 \n"
println("Left Trimmed => ${s.trimStart()}")
println("RightUntrimmed Trimmed => [${s.trimEnd()}]")
println("FullyLeft Trimmed => [${s.trimtrimStart()}]")
println("Right Trimmed => [${s.trimEnd()}]")
}</lang>
println("Fully Trimmed => [${s.trim()}]")
}</syntaxhighlight>
 
{{out}}
<pre>
Untrimmed => [ Rosetta Code
]
Left Trimmed => [Rosetta Code  
]
Right Trimmed => [ Rosetta Code]
Fully Trimmed => [Rosetta Code]
</pre>
 
=={{header|Ksh}}==
Left Trimmed => Rosetta Code
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Strip whitespace from a string/Top and tail
Right Trimmed => Rosetta Code
 
Fully Trimmed => Rosetta Code
# # Variables:
</pre>
#
str=${1:-" This is a test. "}
 
# # Functions:
#
 
# # Function _striphead(str) - Return str with leading while space stripped
#
function _striphead {
typeset _str ; _str="$1"
 
echo "${_str##*(\s)}"
}
 
 
# # Function _striptail(str) - Return str with trailing while space stripped
#
function _striptail {
typeset _str ; _str="$1"
 
while [[ ${_str} != ${_str%+(\s)} ]]; do
_str=${_str%+(\s)}
done
echo "${_str}"
}
 
######
# main #
######
 
printf ">%s< (Unstripped %d chars)\n" "${str}" ${#str}
sstr=$(_striphead "${str}")
printf ">%s< (Strip leading (%d chars))\n" "${sstr}" $(( ${#str}-${#sstr} ))
sstr=$(_striptail "${str}")
printf ">%s< (Strip trailing (%d chars))\n" "${sstr}" $(( ${#str}-${#sstr} ))
sstr=$(_striphead "$(_striptail "${str}")")
printf ">%s< (Strip both (%d chars))\n" "${sstr}" $(( ${#str}-${#sstr} ))</syntaxhighlight>
{{out}}<pre>> This is a test. < (Unstripped 19 chars)
>This is a test. < (Strip leading (1 chars))
> This is a test.< (Strip trailing (3 chars))
>This is a test.< (Strip both (4 chars))</pre>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
initial string : {def string ___String with "_" displaying space_____}
-> string ___String with "_" displaying space_____
Line 1,276 ⟶ 1,659:
trimBoth : {S.replace _+$ by in {S.replace ^_+ by in {string}}}
-> String with "_" displaying space
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
Line 1,282 ⟶ 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,289 ⟶ 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,319 ⟶ 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,353 ⟶ 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,361 ⟶ 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,400 ⟶ 1,783:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,414 ⟶ 1,797:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">str := " \t \r \n String with spaces \t \r \n ";
 
with(StringTools):
Line 1,420 ⟶ 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,436 ⟶ 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,452 ⟶ 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,551 ⟶ 1,934:
 
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre style="height: 25ex; overflow:scroll;">
Line 1,600 ⟶ 1,983:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(setq str " this is a string ")
 
;; trim leading blanks
Line 1,609 ⟶ 1,992:
 
;; trim both leading and trailing blanks
(trim str)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
let s = " \t \nv \r String with spaces \n \t \n f"
echo "'", s, "'"
echo("*** Stripped of leading spaces ***")
echo "'", s.strip(trailing = false), "'"
echo "'", s.strip(leadingtrailing = false), "'"
echo("*** Stripped of trailing spaces ***")
echo "'", s.strip(), "'"</lang>
echo "“", s.strip(leading = false), "”"
echo("*** Stripped of leading and trailing spaces ***")
echo "“", s.strip(), "”"
</syntaxhighlight>
 
{{out}}
<pre>“
String with spaces
*** Stripped of leading spaces ***
“String with spaces
*** Stripped of trailing spaces ***
String with spaces”
*** Stripped of leading and trailing spaces ***
“String with spaces”</pre>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<langsyntaxhighlight lang="oberon2">
MODULE Trim;
IMPORT Out,Strings,SYSTEM;
Line 1,681 ⟶ 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,697 ⟶ 2,099:
{{works with|Cocoa}}
{{works with|GNUstep}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSString (RCExt)
Line 1,749 ⟶ 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,787 ⟶ 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,808 ⟶ 2,210:
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">DEF VAR cc AS CHAR INIT " string with spaces ".
 
MESSAGE
Line 1,814 ⟶ 2,216:
"|" + RIGHT-TRIM( cc ) + "|" SKIP
"|" + TRIM( cc ) + "|"
VIEW-AS ALERT-BOX.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,829 ⟶ 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 1,838 ⟶ 2,240:
print "'", trim($p), "'\n";
print "'", ltrim($p), "'\n";
print "'", rtrim($p), "'\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>constant s = "\ttest\n"
<!--<syntaxhighlight lang="phix">(phixonline)-->
?s
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
?trim_head(s)
<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>
?trim_tail(s)
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
?trim(s)</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
"\ttestt test \n"
"testtest \n"
"\ttestt test"
"test"
</pre>
Line 1,856 ⟶ 2,262:
=={{header|PHP}}==
There is a built-in function that already does this.
<langsyntaxhighlight PHPlang="php"><?php
 
/**
Line 1,866 ⟶ 2,272:
echo '^'.ltrim($string).'$'.PHP_EOL;
echo '^'.rtrim($string).'$'.PHP_EOL;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,873 ⟶ 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 1,882 ⟶ 2,309:
 
(de trimBoth (Str)
(pack (clip (chop Str))) )</langsyntaxhighlight>
Test:
<pre>: (trimLeft " ^G ^I trimmed left ^L ")
Line 1,894 ⟶ 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 1,905 ⟶ 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 1,923 ⟶ 2,350:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">strip :-
In = " There are unwanted blanks here! ",
strip_left(In, OutLeft),
Line 1,952 ⟶ 2,379:
 
strip_action(X) --> X.
</syntaxhighlight>
</lang>
Output :
<pre> ?- strip.
Line 1,970 ⟶ 2,397:
{{works with|SWI-Prolog|7}}
 
<langsyntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,chars) .
 
Line 2,057 ⟶ 2,484:
\+ [_] % .i.e. at end-of-string .
.
</syntaxhighlight>
</lang>
 
 
Line 2,077 ⟶ 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,113 ⟶ 2,540:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>"Top "
Line 2,120 ⟶ 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,129 ⟶ 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,146 ⟶ 2,573:
a quick quack!
 
Stack empty.</langsyntaxhighlight>
 
=={{header|R}}==
 
<langsyntaxhighlight Rlang="r">s <- " Ars Longa "
 
trimws(s)
Line 2,159 ⟶ 2,586:
 
trimws(s, "right")
[1] " Ars Longa"</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,179 ⟶ 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,199 ⟶ 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,241 ⟶ 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,252 ⟶ 2,679:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 01.1.2012 Walter Pachl taking care of all non-printable chars
**********************************************************************/
Line 2,276 ⟶ 2,703:
Say 'sa>'sa'<'<' /* between words */
s0=space(sa,0) /* remove all whitespace */
Say 's0>'s0'<'</langsyntaxhighlight>
Output:
<pre>
Line 2,289 ⟶ 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,311 ⟶ 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,322 ⟶ 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,329 ⟶ 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,368 ⟶ 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,386 ⟶ 2,828:
println("trimRight2: |" + trimRight2(str) + "|")
println("trim : |" + trim(str) + "|")
}</langsyntaxhighlight>
{{out}}
<pre>original : | � String with spaces
Line 2,399 ⟶ 2,841:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,408 ⟶ 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,424 ⟶ 2,866:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">String extend
[
ltrim [
Line 2,443 ⟶ 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,464 ⟶ 2,906:
s2 POS(0) SPAN(stripchars) =
OUTPUT = "Full trim: >" s2 "<"
END</langsyntaxhighlight>
{{out}}
<pre>
Line 2,473 ⟶ 2,915:
Trailing: >� Hello, people of earth!<
Full trim: >Hello, people of earth!<</pre>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">local
open Substring
in
val trimLeft = string o dropl Char.isSpace o full
and trimRight = string o dropr Char.isSpace o full
and trim = string o dropl Char.isSpace o dropr Char.isSpace o full
end</syntaxhighlight>
 
=={{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,488 ⟶ 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,506 ⟶ 2,957:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti-83b">
PROGRAM:WHITESPC
Input Str1
Line 2,534 ⟶ 2,985:
Lbl F
Disp "'"+Str1+"'"
</syntaxhighlight>
</lang>
 
=={{header|TorqueScript}}==
Line 2,555 ⟶ 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,565 ⟶ 3,024:
PRINT "trimmed on top <|",trimmedtop,">|"
PRINT "trimmed on tail <|", trimmedtail,">|"
PRINT "trimmed on both <|", trimmedboth,">|"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,578 ⟶ 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,597 ⟶ 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,624 ⟶ 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,640 ⟶ 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,647 ⟶ 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,657 ⟶ 3,116:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
 
white = ==` !| not @iNC %sI
Line 2,666 ⟶ 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,680 ⟶ 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,700 ⟶ 3,159:
Debug.Print """" & WorksheetFunction.trim(s) & """"
'these functions do not remove tabs or newlines
End Sub</langsyntaxhighlight>{{out}}
<pre>" trim "
"trim "
Line 2,708 ⟶ 3,167:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function LeftTrim(s)
Set regex = New RegExp
Line 2,737 ⟶ 3,196:
WScript.StdOut.WriteLine RightTrim("RosettaCode ")
WScript.StdOut.WriteLine LeftTrim(RightTrim(" RosettaCode "))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,748 ⟶ 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,755 ⟶ 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,764 ⟶ 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,802 ⟶ 3,278:
Text(0, StripTrail(String)); ChOut(0, ^!); CrLf(0);
Text(0, StripTrail(StripLead(String))); ChOut(0, ^!); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 2,812 ⟶ 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 2,845 ⟶ 3,321:
input: ' abcd '
output: 'abcd'
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Trim.png Strip whitespace from a string/Top and tail]
9,476

edits