Strip whitespace from a string/Top and tail: Difference between revisions
Strip whitespace from a string/Top and tail (view source)
Revision as of 16:28, 10 February 2024
, 3 months ago→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Wren}}: Changed to Wren S/H) |
|||
(29 intermediate revisions by 14 users not shown) | |||
Line 18:
=={{header|11l}}==
<
print(s.ltrim((‘ ’, "\t", "\r", "\n")).len)
print(s.rtrim((‘ ’, "\t", "\r", "\n")).len)
print(s.trim((‘ ’, "\t", "\r", "\n")).len)</
{{out}}
Line 28:
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}}==
<
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
Line 40 ⟶ 115:
Put_Line ("'" & Trim (str, Right) & "'");
Put_Line ("'" & Trim (str, Both) & "'");
end StripDemo;</
{{out}}
<pre>
Line 51 ⟶ 126:
=== version 1 ===
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
PROC trim leading whitespace = ( STRING text )STRING:
BEGIN
Line 104 ⟶ 179:
print( ( "trim trailing: """ + trim trailing whitespace( test ) + """", newline ) );
print( ( "trim both: """ + trim whitespace ( test ) + """", newline ) )
)</
{{out}}
<pre>
Line 117 ⟶ 192:
A single procedure that trims leading space, trailing space, or both.
<
string_trim
Trim leading and trailing whitespace from string.
Line 145 ⟶ 220:
print(("string_trim(' foobar '): expected 'foobar'; actual: "
+ string_trim(" foobar "), newline)) FI
)</
=={{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}}
<
-- STRIP WHITESPACE ----------------------------------------------------------
Line 265 ⟶ 396:
|error|:(missing value))'s firstMatchInString:oString options:0 ¬
range:{location:0, |length|:oString's |length|()}) is not missing value
end regexTest</
{{Out}}
<
<--", "-->
Much Ado About Nothing<--", "-->Much Ado About Nothing<--"}</
=={{header|Arturo}}==
<
print [pad "strip all:" 15 ">" strip str "<"]
print [pad "strip leading:" 15 ">" strip.start str "<"]
print [pad "strip trailing:" 15 ">" strip.end str "<"]</
{{out}}
Line 289 ⟶ 420:
=={{header|AutoHotkey}}==
AutoHotkey_L and v2 contain a [http://www.autohotkey.net/~Lexikos/AutoHotkey_L/docs/commands/Trim.htm Trim function]
<
MsgBox % clipboard := "<" LTrim(string) ">`n<" RTrim(string) ">`n<" . Trim(string) ">"</
{{out}}
<pre><abc >
Line 299 ⟶ 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.
<
c = split(str, arr, "")
for ( i = match(str, /[[:graph:]]/); i <= c; i++)
Line 327 ⟶ 458:
print "right = |" trimright(str) "|"
print "both = |" trim(str) "|"
}</
{{out|Output from 26 May 2015}}
Line 347 ⟶ 478:
Simplified for removing [:blank:] (spaces and tabs) or [:space:] (for [ \t\r\n\v\f] ). This method does not work using [:graph:]
<
gsub(/^[[:blank:]]+/,"", str) # Remove leading
gsub(/[[:blank:]]+$/,"", str) # Remove trailing
gsub(/^[[:blank:]]+|[[:blank:]]+$/, "", str) # Remove both
return str;
}</
=={{header|BaCon}}==
<
'---Remove leading whitespace
PRINT CHOP$(" String with spaces "," ",1)
Line 365 ⟶ 496:
'---Remove both leading and trailing whitespace
PRINT CHOP$(" String with spaces "," ",0)
</syntaxhighlight>
=={{header|BASIC}}==
{{works with|QBasic}}
<
mystring$=rtrim(mystring$) ' remove trailing whitespace
mystring$=ltrim(rtrim(mystring$)) ' remove both leading and trailing whitespace</
=={{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}}==
<
WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE
Line 382 ⟶ 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</
=={{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.
<
= s
. @( !arg
Line 419 ⟶ 576:
& out$(str$("trim :[" trim$!string "]"))
&
);</
Output (Notice the effect of the ancient \a (alarm) and \v (vertical tab)):
<pre>Input:[ Hear
Line 440 ⟶ 597:
=={{header|Burlesque}}==
<
blsq ) " this is a string "t[
"this is a string "
Line 447 ⟶ 604:
blsq ) " this is a string "tt
"this is a string"
</syntaxhighlight>
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 495 ⟶ 652:
free(d);
return 0;
}</
==={{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#}}==
<
public class TrimExample
Line 514 ⟶ 704:
return "'" + s + "'";
}
}</
{{out}}
<pre>
Line 523 ⟶ 713:
=={{header|C++}}==
<
#include <string>
#include <iostream>
Line 537 ⟶ 727:
std::cout << "Trimmed on both sides :" << testphrase << "\n" ;
return 0 ;
}</
{{out}}
<PRE>The test phrase is : There are unwanted blanks here!
Line 545 ⟶ 735:
=={{header|Clojure}}==
<
(use 'clojure.string)
(triml " my string ")
Line 553 ⟶ 743:
(trim " \t\r\n my string \t\r\n ")
=> "my string"
</syntaxhighlight>
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
<
DISPLAY "'" FUNCTION TRIM(str, TRAILING) "'"
DISPLAY "'" FUNCTION TRIM(str) "'"</
{{works with|IBM ILE COBOL}}
<
DISPLAY "'" FUNCTION TRIMR(str) "'"
DISPLAY "'" FUNCTION TRIM(str) "'"</
=={{header|Common Lisp}}==
<
(defvar *whitespace* '(#\Space #\Newline #\Tab))
Line 602 ⟶ 792:
(string-right-trim *unicode-whitespace* unicode-str)
; -> " foo bar baz"</
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
def strip_whitepace(s)
puts s.lstrip()
Line 616 ⟶ 806:
# => hello
# => hello
</syntaxhighlight>
=={{header|D}}==
<
void main() {
Line 626 ⟶ 816:
assert(s.stripRight() == " \t \r \n String with spaces");
assert(s.strip() == "String with spaces");
}</
=={{header|Delphi}}/{{header|Pascal}}==
<
{$APPTYPE CONSOLE}
Line 642 ⟶ 832:
Writeln('"' + TrimRight(TEST_STRING) + '"');
Writeln('"' + Trim(TEST_STRING) + '"');
end.</
=={{header|DWScript}}==
{{Trans|Delphi}}
<
PrintLn('"' + TEST_STRING + '"');
PrintLn('"' + TrimLeft(TEST_STRING) + '"');
PrintLn('"' + TrimRight(TEST_STRING) + '"');
PrintLn('"' + Trim(TEST_STRING) + '"');</
=={{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}}==
<
(define witt
" The limits of my world are the limits of my langage. ")
Line 663 ⟶ 885:
(string->html (string-trim-right witt))
→ " The limits of my world are the limits of my langage."
</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x :
<
public program()
Line 675 ⟶ 897:
console.printLine("'", toTrim.trimRight(),"'");
console.printLine("'", toTrim.trim(),"'");
}</
{{out}}
<pre>
Line 684 ⟶ 906:
=={{header|Elixir}}==
<
IO.inspect String.strip(str)
IO.inspect String.rstrip(str)
IO.inspect String.lstrip(str)</
{{out}}
<pre>
Line 696 ⟶ 918:
=={{header|Emacs Lisp}}==
As of Emacs 24.4, the subr-x.el library contains string trimming functions:
<syntaxhighlight lang="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"</syntaxhighlight>
This can be emulated by using regex replacement:
<syntaxhighlight lang="lisp">(defun string-trim-left (str)
(replace-regexp-in-string "^[ \t\r\n]*" "" str))
(defun string-trim-right (str)
(replace-regexp-in-string "[ \t\r\n]*$" "" str))
(defun string-trim (str)
(string-trim-left (string-trim-right str)))</syntaxhighlight>
=={{header|Erlang}}==
<
1> string:strip(" Hello World! ", left). %remove leading whitespaces
"Hello World! "
Line 757 ⟶ 946:
3> string:strip(" Hello World! ", both). % remove both leading and trailing whitespace
"Hello World!"
</syntaxhighlight>
=={{header|Euphoria}}==
Line 767 ⟶ 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.
<
include std/text.e
Line 783 ⟶ 972:
end for
any_key()</
Output:<pre>
String Trimmed is now: A B C
Line 797 ⟶ 986:
=={{header|F_Sharp|F#}}==
<
let main args =
printfn "%A" (args.[0].TrimStart())
printfn "%A" (args.[0].TrimEnd())
printfn "%A" (args.[0].Trim())
0</
<pre>
>rosetta " a string "
Line 811 ⟶ 1,000:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
" test string " [ blank? ] trim ! leading and trailing
" test string " [ blank? ] trim-head ! only leading
" test string " [ blank? ] trim-tail ! only trailing</
=={{header|Forth}}==
Line 821 ⟶ 1,010:
After the string processing is completed on the stack the program can print or copy back to memory as required.
<
begin
over c@ bl = \ fetch character at addr, test if blank (space)
Line 827 ⟶ 1,016:
\ cut 1 leading character by incrementing address & decrementing length
1 /string \ "cut-string"
repeat ;</
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 ; </
Test at the Forth console
<pre>: mystring s" Trim this string. " ;
Line 847 ⟶ 1,036:
=={{header|FreeBASIC}}==
<
Const whitespace = !" \t\n\v\f\r"
Line 870 ⟶ 1,059:
Print "Right trimmed" , "=> Length = "; Len(s2)
Print "Fully trimmed" , "=> Length = "; Len(s3)
Sleep</
{{out}}
Line 885 ⟶ 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]'''
<
Dim sString As String = " Hello world! "
Line 897 ⟶ 1,129:
Print Trim(sString) & "\t\tString length = " & Len(Trim(sString)) & " - String with both leading and trailing whitespace removed"
End</
Output:
<pre>
Line 907 ⟶ 1,139:
=={{header|Go}}==
<
import (
Line 928 ⟶ 1,160:
func show(label, str string) {
fmt.Printf("%s: |%s| %v\n", label, str, []rune(str))
}</
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 943 ⟶ 1,175:
=={{header|Groovy}}==
Solution uses StringUtils class from [http://commons.apache.org/lang/ Apache Commons "Lang" library]:
<
@Grab('org.apache.commons:commons-lang3:3.0.1')
import static org.apache.commons.lang3.StringUtils.*
Line 964 ⟶ 1,196:
println '============\n\nRight Stripped\n------------'
printTest stripEnd(abc, null)
println '============'</
{{out}}
<pre>Unstripped
Line 991 ⟶ 1,223:
=={{header|Haskell}}==
<
import Data.List (dropWhileEnd)
Line 1,001 ⟶ 1,233:
trim :: String -> String
trim = trimLeft . trimRight</
=={{header|Icon}} and {{header|Unicon}}==
This solution takes the phrase "other such characters that have no corresponding graphical representation" quite literallly.
<
unp := &cset[1+:32]++' \t'++&cset[127:0] # all 'unprintable' chars
s := " Hello, people of earth! "
Line 1,012 ⟶ 1,244:
write("trailing trim: '",trim(s,unp),"'")
write("full trim: '",reverse(trim(reverse(trim(s,unp)),unp)),"'")
end</
{{out|Sample run}}
<pre>->trim
Line 1,023 ⟶ 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.
<
quote dlb ' String with spaces ' NB. delete leading blanks
'String with spaces '
Line 1,029 ⟶ 1,261:
' String with spaces'
quote dltb ' String with spaces ' NB. delete leading and trailing blanks
'String with spaces'</
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.
<
'String with spaces'</
These existing definitions can be easily amended to include whitespace other than spaces if 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</
=={{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,048 ⟶ 1,320:
Left trim and right trim taken from [http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html here].
<
public static String ltrim(String s) {
int i = 0;
Line 1,075 ⟶ 1,347:
System.out.printf("[%s]\n", trim(s));
}
}</
===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:
<
int offset = 0;
while (offset < s.length()) {
Line 1,099 ⟶ 1,371:
return s.substring(0, offset);
}
</syntaxhighlight>
=={{header|Javascript}}==
{{works with|Node.js}}
{{works with|ECMAScript standard|2015}}
<
let s = " \t String with spaces \t ";
// a future version of ECMAScript will have trimStart(). Some current
Line 1,114 ⟶ 1,386:
console.log("trimmed right: '" + s.replace(/\s+$/,'') + "'");
console.log("trimmed both: '" + s.trim() + "'");
}</
{{Output}}
<pre>original: ' String with spaces '
Line 1,125 ⟶ 1,397:
{{Trans|Haskell}}
<
'use strict';
Line 1,173 ⟶ 1,445:
})();
</syntaxhighlight>
{{Out}}
Line 1,189 ⟶ 1,461:
Notice that since jq strings are JSON strings, one must, for example, write "\\s" for the regex '\s'.
<
def rstrip: sub( "[\\s\\p{Cc}]+$"; "" );
def strip: lstrip | rstrip;</
'''Examples''':
<
"lstrip: \(lstrip)",
"rstrip: \(rstrip)",
Line 1,204 ⟶ 1,476:
"\u0001 \u0002 <- ^A ^B"
) | demo
</syntaxhighlight>
{{Out}}
<
"lstrip: String with spaces \t \r \n "
"rstrip: \t \r \n String with spaces"
Line 1,214 ⟶ 1,486:
"lstrip: <- ^A ^B"
"rstrip: \u0001 \u0002 <- ^A ^B"
"strip: <- ^A ^B"</
=={{header|Jsish}}==
Using echo-mode unitTest lines. Lines starting with semicolon are echoed and captured during test.
<
/* Strip whitespace from string, in Jsi */
var str = ' \n \t String with whitespace \t \n ';
Line 1,252 ⟶ 1,524:
str.trim() ==> String with whitespace
=!EXPECTEND!=
*/</
{{out}}
Line 1,275 ⟶ 1,547:
=={{header|Julia}}==
{{trans|Python}}
<
" \t \r \n String with spaces \t \r \n "
Line 1,285 ⟶ 1,557:
julia> strip(s)
"String with spaces"</
=={{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,292 ⟶ 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.
<
val s = " \tRosetta Code \r \u2009 \n"
println("Untrimmed => [$s]")
Line 1,298 ⟶ 1,585:
println("Right Trimmed => [${s.trimEnd()}]")
println("Fully Trimmed => [${s.trim()}]")
}</
{{out}}
Line 1,309 ⟶ 1,596:
Fully Trimmed => [Rosetta Code]
</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# Strip whitespace from a string/Top and tail
# # Variables:
#
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}}==
<
initial string : {def string ___String with "_" displaying space_____}
-> string ___String with "_" displaying space_____
Line 1,323 ⟶ 1,659:
trimBoth : {S.replace _+$ by in {S.replace ^_+ by in {string}}}
-> String with "_" displaying space
</syntaxhighlight>
=={{header|Lasso}}==
Line 1,329 ⟶ 1,665:
The '>' and '<' strings have been included in this example to demonstrate the whitespace trim.
<
'>' + (' \t Hello')->trim& + '<'
Line 1,336 ⟶ 1,672:
// String with both leading and trailing whitespace removed
'>' + (' \t Hello \t ')->trim& + '<'</
=={{header|Liberty BASIC}}==
<
'LB TRIM$ removes characters with codes 0..31 as well as a space(code 32)
Line 1,366 ⟶ 1,702:
end function
</syntaxhighlight>
=={{header|Logtalk}}==
Using atoms for representing strings and assuming an ASCII text encoding:
<
:- object(whitespace).
Line 1,400 ⟶ 1,736:
:- end_object.
</syntaxhighlight>
Sample output:
<
| ?- whitespace::trim('\n\t Rosetta Code \t\n', TrimLeft, TrimRight, TrimBoth).
TrimLeft = 'Rosetta Code \t\n',
Line 1,408 ⟶ 1,744:
TrimBoth = 'Rosetta Code'
yes
</syntaxhighlight>
=={{header|Lua}}==
<
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*$" ) ) )</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
filter$=chr$(0)
Line 1,447 ⟶ 1,783:
}
Checkit
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,461 ⟶ 1,797:
=={{header|Maple}}==
<
with(StringTools):
Line 1,467 ⟶ 1,803:
TrimLeft(str);
TrimRight(str);
Trim(str);</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
<
str = str(1:find(~isspace(str),1,'last'));
% remove leading whitespaces
Line 1,483 ⟶ 1,819:
% a built-in function, removes leading and trailing whitespaces
str = strtrim(str);</
=={{header|Mercury}}==
<
:- interface.
Line 1,499 ⟶ 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).</
=={{header|Nemerle}}==
<
WriteLine(str.TrimStart());
WriteLine(str.TrimEnd());
WriteLine(str.Trim()); // both ends at once, of course, internal whitespace is preserved in all 3</
=={{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:
<
options replace format comments java crossref symbols nobinary
Line 1,598 ⟶ 1,934:
return
</syntaxhighlight>
'''Output:'''
<pre style="height: 25ex; overflow:scroll;">
Line 1,647 ⟶ 1,983:
=={{header|NewLISP}}==
<
;; trim leading blanks
Line 1,656 ⟶ 1,992:
;; trim both leading and trailing blanks
(trim str)</
=={{header|Nim}}==
<
let s = "\t \v \r String with spaces \n \t \f"
Line 1,669 ⟶ 2,005:
echo("*** Stripped of leading and trailing spaces ***")
echo "“", s.strip(), "”"
</syntaxhighlight>
{{out}}
Line 1,688 ⟶ 2,024:
=={{header|Oberon-2}}==
Oxford Oberon-2
<
MODULE Trim;
IMPORT Out,Strings,SYSTEM;
Line 1,747 ⟶ 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>
Output:
<pre>
Line 1,763 ⟶ 2,099:
{{works with|Cocoa}}
{{works with|GNUstep}}
<
@interface NSString (RCExt)
Line 1,815 ⟶ 2,151:
}
return 0;
}</
=={{header|OCaml}}==
<
let rec aux i =
if i >= len then None
Line 1,853 ⟶ 2,189:
match right_pos s len with
| Some i -> String.sub s 0 (i + 1)
| None -> ""</
we put the previous code in a file called "trim.ml", and then we test these functions in the toplevel:
<pre>$ ocaml
Line 1,874 ⟶ 2,210:
=={{header|OpenEdge/Progress}}==
<
MESSAGE
Line 1,880 ⟶ 2,216:
"|" + RIGHT-TRIM( cc ) + "|" SKIP
"|" + TRIM( cc ) + "|"
VIEW-AS ALERT-BOX.</
{{out}}
<pre>
Line 1,895 ⟶ 2,231:
=={{header|Perl}}==
<
sub rtrim { shift =~ s/\s+$//r }
sub trim { ltrim rtrim shift }
Line 1,904 ⟶ 2,240:
print "'", trim($p), "'\n";
print "'", ltrim($p), "'\n";
print "'", rtrim($p), "'\n";</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<span style="color: #008080;">
<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>
<!--</
{{out}}
<pre>
"\
"
"\
"test"
</pre>
Line 1,925 ⟶ 2,262:
=={{header|PHP}}==
There is a built-in function that already does this.
<
/**
Line 1,935 ⟶ 2,272:
echo '^'.ltrim($string).'$'.PHP_EOL;
echo '^'.rtrim($string).'$'.PHP_EOL;
</syntaxhighlight>
{{out}}
<pre>
Line 1,942 ⟶ 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}}==
<
(pack (flip (trim (flip (chop Str))))) )
Line 1,951 ⟶ 2,309:
(de trimBoth (Str)
(pack (clip (chop Str))) )</
Test:
<pre>: (trimLeft " ^G ^I trimmed left ^L ")
Line 1,963 ⟶ 2,321:
=={{header|PL/I}}==
<
put ( trim(text, '', ' ') ); /* trims trailing blanks. */
put ( trim(text) ); /* trims leading and trailing */
/* blanks. */</
To remove any white-space character(s) in a portable way:-
<
((substr(collate(), 1, 32) || ' '));
put ( trim(text, whitespace) ); /* trims leading white space. */
Line 1,974 ⟶ 2,332:
put ( trim(text, whitespace, whitespace) );
/* trims leading and trailing */
/* white space. */</
=={{header|PowerShell}}==
<syntaxhighlight 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>
<b>Output:</b>
<pre>
Line 1,992 ⟶ 2,350:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
In = " There are unwanted blanks here! ",
strip_left(In, OutLeft),
Line 2,021 ⟶ 2,379:
strip_action(X) --> X.
</syntaxhighlight>
Output :
<pre> ?- strip.
Line 2,039 ⟶ 2,397:
{{works with|SWI-Prolog|7}}
<
:- system:set_prolog_flag(double_quotes,chars) .
Line 2,126 ⟶ 2,484:
\+ [_] % .i.e. at end-of-string .
.
</syntaxhighlight>
Line 2,146 ⟶ 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.
<
#whitespace$ = " " + Chr($9) + Chr($A) + Chr($B) + Chr($C) + Chr($D) + Chr($1C) + Chr($1D) + Chr($1E) + Chr($1F)
Line 2,182 ⟶ 2,540:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>"Top "
Line 2,189 ⟶ 2,547:
=={{header|Python}}==
<
>>> s
' \t \r \n String with spaces \t \r \n '
Line 2,198 ⟶ 2,556:
>>> s.strip()
'String with spaces'
>>> </
=={{header|Quackery}}==
As a dialogue in the Quackery shell.
<
... [ trim trim-trailing ] is trim-both-ends ( $ --> $ )
... $ ' a quick quack ' echo$ say "!" cr
Line 2,215 ⟶ 2,573:
a quick quack!
Stack empty.</
=={{header|R}}==
<
trimws(s)
Line 2,228 ⟶ 2,586:
trimws(s, "right")
[1] " Ars Longa"</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 2,248 ⟶ 2,606:
;; can also normalize spaces:
(string-normalize-spaces (string-trim str)) ; -> "foo bar"
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2020.08.1}}
<syntaxhighlight lang="raku"
say $s.trim;
say $s.trim.raku;
say $s.trim-leading.raku;
say $s.trim-trailing.raku;</
{{Output}}
Line 2,268 ⟶ 2,626:
=={{header|Red}}==
<
== "remove leading white space "
>> trim/tail " remove trailing white space "
== " remove trailing white space"
>> trim " remove both white spaces "
== "remove both white spaces"</
=={{header|Retro}}==
<
'__this_is_a_test___ s:trim-right
'__this_is_a_test___ s:trim</
=={{header|REXX}}==
===version 1===
<
yyy=" this is a string that has leading/embedded/trailing blanks, fur shure. "
say 'YYY──►'yyy"◄──" /*display the original string + fence. */
Line 2,310 ⟶ 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. */</
'''output'''
<pre>
Line 2,321 ⟶ 2,679:
===version 2===
<
* 01.1.2012 Walter Pachl taking care of all non-printable chars
**********************************************************************/
Line 2,345 ⟶ 2,703:
Say 'sa>'sa'<'<' /* between words */
s0=space(sa,0) /* remove all whitespace */
Say 's0>'s0'<'</
Output:
<pre>
Line 2,358 ⟶ 2,716:
=={{header|Ring}}==
<
aList = " Welcome to the Ring Programming Language "
see aList + nl
see trim(aList) + nl
</syntaxhighlight>
=={{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}}==
<
p s
p s.lstrip # remove leading whitespaces
p s.rstrip # remove trailing whitespaces
p s.strip # remove both leading and trailing whitespace
</syntaxhighlight>
{{out}}
<pre>
Line 2,380 ⟶ 2,753:
=={{header|Run BASIC}}==
<
print " Top:";trim$(string$+"|") ' top left trim
print "Bottom:";trim$("|"+string$) ' bottom right trim
print " Both:";trim$(string$) ' both left and right
end</
<pre> Top:abcdefg
Bottom: abcdefg
Line 2,391 ⟶ 2,764:
=={{header|Rust}}==
<
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,398 ⟶ 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");
}</
=={{header|Sather}}==
<
ltrim(s :STR) :STR is
i ::= 0;
Line 2,437 ⟶ 2,810:
#OUT + trim(p).pretty + "\n";
end;
end;</
=={{header|Scala}}==
<
def trimRight(str: String) = str take (str.lastIndexWhere(!_.isWhitespace) + 1)
Line 2,455 ⟶ 2,828:
println("trimRight2: |" + trimRight2(str) + "|")
println("trim : |" + trim(str) + "|")
}</
{{out}}
<pre>original : | � String with spaces
Line 2,468 ⟶ 2,841:
=={{header|Seed7}}==
<
const proc: main is func
Line 2,477 ⟶ 2,850:
writeln(rtrim(testStri));
writeln(trim(testStri));
end func;</
=={{header|Sidef}}==
<
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</
{{out}}
<pre>
Line 2,493 ⟶ 2,866:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
[
ltrim [
Line 2,512 ⟶ 2,885:
('"%1"' % {a ltrim}) displayNl.
('"%1"' % {a rtrim}) displayNl.
('"%1"' % {a trim}) displayNl.</
=={{header|SNOBOL4}}==
<
s2 = CHAR(3) s2 CHAR(134)
&ALPHABET TAB(33) . prechars
Line 2,533 ⟶ 2,906:
s2 POS(0) SPAN(stripchars) =
OUTPUT = "Full trim: >" s2 "<"
END</
{{out}}
<pre>
Line 2,544 ⟶ 2,917:
=={{header|Standard ML}}==
<
open Substring
in
Line 2,550 ⟶ 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</
=={{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.
<
"("+strtrim(s)+")"
(ars longa)
Line 2,566 ⟶ 2,939:
"("+stritrim(s)+")"
( ars longa )</
=={{header|Tcl}}==
Whitespace stripping is done with <code>string trim</code> and related commands:
<
puts "original: >$str<"
puts "trimmed head: >[string trimleft $str]<"
puts "trimmed tail: >[string trimright $str]<"
puts "trimmed both: >[string trim $str]<"</
{{out}}
<pre>
Line 2,584 ⟶ 2,957:
=={{header|TI-83 BASIC}}==
<
PROGRAM:WHITESPC
Input Str1
Line 2,612 ⟶ 2,985:
Lbl F
Disp "'"+Str1+"'"
</syntaxhighlight>
=={{header|TorqueScript}}==
Line 2,633 ⟶ 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}}==
<
str= " sentence w/whitespace before and after "
trimmedtop=EXTRACT (str,":<|<> :"|,0)
Line 2,643 ⟶ 3,024:
PRINT "trimmed on top <|",trimmedtop,">|"
PRINT "trimmed on tail <|", trimmedtail,">|"
PRINT "trimmed on both <|", trimmedboth,">|"</
{{out}}
<pre>
Line 2,656 ⟶ 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.
<
@ (next :list in)
@/[ \t]*/@out
Line 2,675 ⟶ 3,056:
trim_right: [@{line_of_input :filter (:fun trim_right)}]
trim_both: [@{line_of_input :filter ((:fun trim_left) (:fun trim_right))}]
@(end)</
{{out}}
<pre>$ echo "" | txr trim.txr -
Line 2,702 ⟶ 3,083:
Trimming whitespace from both ends is a builtin:
<
"a b"</
An unnecessarily cryptic, though educational, left trim:
<
"a b "</
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,718 ⟶ 3,099:
Lastly, a pedestrian right trim:
<
(for ()
((and (> (length str) 0) (chr-isspace [str -1])) str)
Line 2,725 ⟶ 3,106:
(format t "{~a}\n" (trim-right " "))
(format t "{~a}\n" (trim-right "a "))
(format t "{~a}\n" (trim-right ""))</
Output:
Line 2,735 ⟶ 3,116:
=={{header|Ursala}}==
<
white = ==` !| not @iNC %sI
Line 2,744 ⟶ 3,125:
#cast %sgUL
main = <.trim_left,trim_right,trim_both> ' string with spaces '</
* 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,758 ⟶ 3,139:
=={{header|Vala}}==
===Strip Leading White Space===
<
string s_chug = s.chug();</
===Strip Trailing White Space===
<
string s_chomp = s.chomp();</
===Strip Leading & Trailing White Space===
<
string s_strip = s.strip();</
=={{header|VBA}}==
<
'LTrim trims leading spaces
'RTrim trims tailing spaces
Line 2,778 ⟶ 3,159:
Debug.Print """" & WorksheetFunction.trim(s) & """"
'these functions do not remove tabs or newlines
End Sub</
<pre>" trim "
"trim "
Line 2,786 ⟶ 3,167:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function LeftTrim(s)
Set regex = New RegExp
Line 2,815 ⟶ 3,196:
WScript.StdOut.WriteLine RightTrim("RosettaCode ")
WScript.StdOut.WriteLine LeftTrim(RightTrim(" RosettaCode "))
</syntaxhighlight>
{{Out}}
Line 2,826 ⟶ 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.
<
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,833 ⟶ 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</
{{out}}
Line 2,842 ⟶ 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}}==
<
string 0; \use zero-terminated string convention
Line 2,880 ⟶ 3,278:
Text(0, StripTrail(String)); ChOut(0, ^!); CrLf(0);
Text(0, StripTrail(StripLead(String))); ChOut(0, ^!); CrLf(0);
]</
Output:
Line 2,890 ⟶ 3,288:
=={{header|Yabasic}}==
<
print "--",ltrim$(s$),"--"
print "--",rtrim$(s$),"--"
print "--",trim$(s$),"--"</
=={{header|zkl}}==
Remove white space from both end of string:
<
<
try{ while(s[n].isSpace()){ n+=1 } }catch{""}fallthrough{ s[n,*] }
}
removeLeadingWS("\t\n hoho\n\t\ ") //-->"hoho\n\t "
removeLeadingWS("") //-->""</
<
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\ ") //-->""</
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: trim_left
input: ' abcd'
Line 2,923 ⟶ 3,321:
input: ' abcd '
output: 'abcd'
</syntaxhighlight>
=={{header|Zoea Visual}}==
|