Strip a set of characters from a string: Difference between revisions
PascalABC.NET |
|||
(291 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{task|String manipulation}} |
{{task|String manipulation}} |
||
[[Category:Strings]] |
|||
The task is to create a function that strips a set of characters from a string. The function should take two arguments: the first argument being a string to stripped and the second, a string containing the set of characters to be stripped. The returned string should contain the first string, stripped of any characters in the second argument: |
|||
;Task: |
|||
<lang pseudocode> print stripchars("She was a soul stripper. She took my heart!","aei") |
|||
Create a function that strips a set of characters from a string. |
|||
Sh ws soul strppr. Sh took my hrt!</lang> |
|||
The function should take two arguments: |
|||
:::# a string to be stripped |
|||
:::# a string containing the set of characters to be stripped |
|||
<br> |
|||
The returned string should contain the first string, stripped of any characters in the second argument: |
|||
<syntaxhighlight lang="pseudocode"> print stripchars("She was a soul stripper. She took my heart!","aei") |
|||
Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
{{Template:Strings}} |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">F stripchars(s, chars) |
|||
R s.filter(c -> c !C @chars).join(‘’) |
|||
print(stripchars(‘She was a soul stripper. She took my heart!’, ‘aei’))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|360 Assembly}}== |
|||
{{trans|PL/I}} |
|||
The program uses two ASSIST macro (XDECO,XPRNT) to keep the code as short as possible. |
|||
<syntaxhighlight lang="360asm">* Strip a set of characters from a string 07/07/2016 |
|||
STRIPCH CSECT |
|||
USING STRIPCH,R13 base register |
|||
B 72(R15) skip savearea |
|||
DC 17F'0' savearea |
|||
STM R14,R12,12(R13) prolog |
|||
ST R13,4(R15) " <- |
|||
ST R15,8(R13) " -> |
|||
LR R13,R15 " addressability |
|||
LA R1,PARMLIST parameter list |
|||
BAL R14,STRIPCHR c3=stripchr(c1,c2) |
|||
LA R2,PG @pg |
|||
LH R3,C3 length(c3) |
|||
LA R4,C3+2 @c3 |
|||
LR R5,R3 length(c3) |
|||
MVCL R2,R4 pg=c3 |
|||
XPRNT PG,80 print buffer |
|||
L R13,4(0,R13) epilog |
|||
LM R14,R12,12(R13) " restore |
|||
XR R15,R15 " rc=0 |
|||
BR R14 exit |
|||
PARMLIST DC A(C3) @c3 |
|||
DC A(C1) @c1 |
|||
DC A(C2) @c2 |
|||
C1 DC H'43',CL62'She was a soul stripper. She took my heart!' |
|||
C2 DC H'3',CL14'aei' c2 [varchar(14)] |
|||
C3 DS H,CL62 c3 [varchar(62)] |
|||
PG DC CL80' ' buffer [char(80)] |
|||
*------- stripchr ----------------------------------------------------- |
|||
STRIPCHR L R9,0(R1) @parm1 |
|||
L R2,4(R1) @parm2 |
|||
L R3,8(R1) @parm3 |
|||
MVC PHRASE(64),0(R2) phrase=parm2 |
|||
MVC REMOVE(16),0(R3) remove=parm3 |
|||
SR R8,R8 k=0 |
|||
LA R6,1 i=1 |
|||
LOOPI CH R6,PHRASE do i=1 to length(phrase) |
|||
BH ELOOPI " |
|||
LA R4,PHRASE+1 @phrase |
|||
AR R4,R6 +i |
|||
MVC CI(1),0(R4) ci=substr(phrase,i,1) |
|||
MVI OK,X'01' ok='1'B |
|||
LA R7,1 j=1 |
|||
LOOPJ CH R7,REMOVE do j=1 to length(remove) |
|||
BH ELOOPJ " |
|||
LA R4,REMOVE+1 @remove |
|||
AR R4,R7 +j |
|||
MVC CJ,0(R4) cj=substr(remove,j,1) |
|||
CLC CI,CJ if ci=cj |
|||
BNE CINECJ then |
|||
MVI OK,X'00' ok='0'B |
|||
B ELOOPJ leave j |
|||
CINECJ LA R7,1(R7) j=j+1 |
|||
B LOOPJ end do j |
|||
ELOOPJ CLI OK,X'01' if ok |
|||
BNE NOTOK then |
|||
LA R8,1(R8) k=k+1 |
|||
LA R4,RESULT+1 @result |
|||
AR R4,R8 +k |
|||
MVC 0(1,R4),CI substr(result,k,1)=ci |
|||
NOTOK LA R6,1(R6) i=i+1 |
|||
B LOOPI end do i |
|||
ELOOPI STH R8,RESULT length(result)=k |
|||
MVC 0(64,R9),RESULT return(result) |
|||
BR R14 return to caller |
|||
CI DS CL1 ci [char(1)] |
|||
CJ DS CL1 cj [char(1)] |
|||
OK DS X ok [boolean] |
|||
PHRASE DS H,CL62 phrase [varchar(62)] |
|||
REMOVE DS H,CL14 remove [varchar(14)] |
|||
RESULT DS H,CL62 result [varchar(62)] |
|||
* ---- ------------------------------------------------------- |
|||
YREGS |
|||
END STRIPCH</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|8080 Assembly}}== |
|||
<syntaxhighlight lang="8080asm"> org 100h |
|||
jmp demo |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
;;; Strip a set of chracters from a string, in place. |
|||
;;; Input: |
|||
;;; DE = $-terminated string to be stripped |
|||
;;; HL = $-terminated string containing characters to strip |
|||
stripchars: push h ; Store characters to strip on stack. |
|||
mov b,d ; Copy input string pointer to BC. This will be |
|||
mov c,e ; the target pointer. |
|||
stripchr: ldax d ; Copy current character from [DE] to [BC] |
|||
stax b |
|||
cpi '$' ; Done? |
|||
jz stripdone |
|||
pop h ; Get string of characters to strip. |
|||
push h |
|||
stripsrch: mvi a,'$' ; At the end? |
|||
cmp m |
|||
jz srchdone |
|||
ldax d ; Does it match the character in the input? |
|||
cmp m |
|||
jz srchfound |
|||
inx h ; Look at next character to strip |
|||
jmp stripsrch |
|||
srchfound: dcx b ; Found: copy next character over it later. |
|||
srchdone: inx b ; Increment both pointers |
|||
inx d |
|||
jmp stripchr |
|||
stripdone: pop h ; Remove temporary variable from stack |
|||
ret ; Done |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
demo: lxi d,string ; Strip from the string, |
|||
lxi h,remove ; the characters to remove. |
|||
call stripchars |
|||
lxi d,string ; Print the result. |
|||
mvi c,9 |
|||
jmp 5 |
|||
string: db 'She was a soul stripper. She took my heart!$' |
|||
remove: db 'aei$'</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|8086 Assembly}}== |
|||
<syntaxhighlight lang="asm"> bits 16 |
|||
cpu 8086 |
|||
section .text |
|||
org 100h |
|||
jmp demo |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
;;; Strip a set of characters from a string, in place. |
|||
;;; Input: |
|||
;;; DS:DI = $-terminated string to be stripped. |
|||
;;; DS:SI = $-terminated string containing chars to strip |
|||
stripchars: mov bx,di ; Copy string ptr to use as target ptr |
|||
mov dx,si ; Copy ptr to characters to strip |
|||
.char: mov al,[di] ; Copy character |
|||
mov [bx],al |
|||
cmp al,'$' ; Done? |
|||
je .done |
|||
mov si,dx ; See if character should be stripped |
|||
.search: mov ah,[si] |
|||
cmp ah,'$' ; End of characters to strip? |
|||
je .srchdone |
|||
cmp ah,al ; Does it match the current character? |
|||
je .srchfound |
|||
inc si ; Try next character |
|||
jmp .search |
|||
.srchfound: dec bx ; Found - decrement target pointer |
|||
.srchdone: inc bx ; Increment both pointers |
|||
inc di |
|||
jmp .char |
|||
.done: ret |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
demo: mov di,string ; Strip from the string, |
|||
mov si,remove ; the characters to remove. |
|||
call stripchars |
|||
mov dx,string ; Print the result |
|||
mov ah,9 |
|||
int 21h |
|||
ret |
|||
section .data |
|||
string: db 'She was a soul stripper. She took my heart!$' |
|||
remove: db 'aei$'</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|ABC}}== |
|||
<syntaxhighlight lang="abc">HOW TO RETURN s stripchars chs: |
|||
PUT "" IN result |
|||
FOR c IN s: |
|||
IF c not.in chs: PUT result^c IN result |
|||
RETURN result |
|||
WRITE "She was a soul stripper. She took my heart!" stripchars "aei"/</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">PROC Strip(CHAR ARRAY text,chars,res) |
|||
BYTE i,j,size,found |
|||
CHAR c |
|||
size=0 |
|||
FOR i=1 TO text(0) |
|||
DO |
|||
c=text(i) found=0 |
|||
FOR j=1 TO chars(0) |
|||
DO |
|||
IF c=chars(j) THEN |
|||
found=1 EXIT |
|||
FI |
|||
OD |
|||
IF found=0 THEN |
|||
size==+1 |
|||
res(size)=c |
|||
FI |
|||
OD |
|||
res(0)=size |
|||
RETURN |
|||
PROC Main() |
|||
CHAR ARRAY |
|||
text="She was a soul stripper. She took my heart!", |
|||
chars="aei", result(255) |
|||
Strip(text,chars,result) |
|||
PrintE("String to be stripped:") |
|||
PrintF("""%S""%E%E",text) |
|||
PrintE("Characters to be stripped:") |
|||
PrintF("""%S""%E%E",chars) |
|||
PrintE("Stripped string:") |
|||
PrintF("""%S""%E%E",result) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Strip_a_set_of_characters_from_a_string.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
String to be stripped: |
|||
"She was a soul stripper. She took my heart!" |
|||
Characters to be stripped: |
|||
"aei" |
|||
Stripped string: |
|||
"Sh ws soul strppr. Sh took my hrt!" |
|||
</pre> |
|||
=={{header|Ada}}== |
|||
<syntaxhighlight lang="ada">with Ada.Text_IO; |
|||
procedure Strip_Characters_From_String is |
|||
function Strip(The_String: String; The_Characters: String) |
|||
return String is |
|||
Keep: array (Character) of Boolean := (others => True); |
|||
Result: String(The_String'Range); |
|||
Last: Natural := Result'First-1; |
|||
begin |
|||
for I in The_Characters'Range loop |
|||
Keep(The_Characters(I)) := False; |
|||
end loop; |
|||
for J in The_String'Range loop |
|||
if Keep(The_String(J)) then |
|||
Last := Last+1; |
|||
Result(Last) := The_String(J); |
|||
end if; |
|||
end loop; |
|||
return Result(Result'First .. Last); |
|||
end Strip; |
|||
S: String := "She was a soul stripper. She took my heart!"; |
|||
begin -- main |
|||
Ada.Text_IO.Put_Line(Strip(S, "aei")); |
|||
end Strip_Characters_From_String;</syntaxhighlight> |
|||
{{out}} |
|||
<pre>> ./strip_characters_from_string |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">text |
|||
stripchars1(data b, text w) |
|||
{ |
|||
integer p; |
|||
p = b.look(0, w); |
|||
while (p < ~b) { |
|||
b.delete(p); |
|||
p += b.look(p, w); |
|||
} |
|||
b; |
|||
} |
|||
text |
|||
stripchars2(data b, text w) |
|||
{ |
|||
b.drop(w); |
|||
} |
|||
integer |
|||
main(void) |
|||
{ |
|||
o_text(stripchars1("She was a soul stripper. She took my heart!", "aei")); |
|||
o_newline(); |
|||
o_text(stripchars2("She was a soul stripper. She took my heart!", "aei")); |
|||
o_newline(); |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
=={{header|ALGOL 68}}== |
|||
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}} |
|||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}} |
|||
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}} |
|||
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script # |
|||
PROC strip chars = (STRING mine, ore)STRING: ( |
|||
STRING out := ""; |
|||
FOR i FROM LWB mine TO UPB mine DO |
|||
IF NOT char in string(mine[i], LOC INT, ore) THEN |
|||
out +:= mine[i] |
|||
FI |
|||
OD; |
|||
out[@LWB mine] |
|||
); |
|||
printf(($gl$,stripchars("She was a soul stripper. She took my heart!","aei")))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|ALGOL W}}== |
|||
<syntaxhighlight lang="algolw">begin |
|||
% returns s with the characters in remove removed % |
|||
% as all strings in Algol W are fixed length, the length of remove % |
|||
% must be specified in removeLength % |
|||
string(256) procedure stripCharacters( string(256) value s, remove |
|||
; integer value removeLength |
|||
) ; |
|||
begin |
|||
string(256) resultText; |
|||
integer tPos; |
|||
resultText := " "; |
|||
tPos := 0; |
|||
for sPos := 0 until 255 do begin |
|||
logical keepCharacter; |
|||
string(1) c; |
|||
c := s( sPos // 1 ); |
|||
keepCharacter := true; |
|||
for rPos := 0 until removeLength - 1 do begin |
|||
if remove( rPos // 1 ) = c then begin |
|||
% have a character that should be removed % |
|||
keepCharacter := false; |
|||
goto endSearch |
|||
end if_have_a_character_to_remove ; |
|||
end for_rPos ; |
|||
endSearch: |
|||
if keepCharacter then begin |
|||
resultText( tPos // 1 ) := c; |
|||
tPos := tPos + 1 |
|||
end if_keepCharacter |
|||
end for_sPos ; |
|||
resultText |
|||
end stripCharacters ; |
|||
% task test case % |
|||
begin |
|||
string(256) ex, stripped; |
|||
ex := "She was a soul stripper. She took my heart!"; |
|||
stripped := stripCharacters( ex, "aei", 3 ); |
|||
write( "text: ", ex( 0 // 64 ) ); |
|||
write( " ->: ", stripped( 0 // 64 ) ) |
|||
end |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
text: She was a soul stripper. She took my heart! |
|||
->: Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Amazing Hopper}}== |
|||
<p>Amazing Hopper! Flavour "Jambo".</p> |
|||
<syntaxhighlight lang="Amazing Hopper"> |
|||
#include <jambo.h> |
|||
Main |
|||
c = ".$%#\tEste@@@ mensaje será purgado!$$$" |
|||
{"Hopper assembler:\n\n"} |
|||
{"$%#@.\t", c} str to utf8, delete char, {"\n"} print |
|||
Printnl ("\nHopper Jambo formal syntax:\n\n", Char del ( "$%#@.\t", Utf8( c ) ) ) |
|||
Set ' "\nHopper Jambo Natural syntax:\n\n", "$%#@.\t", c', Get utf8, and delete char |
|||
then print with newline |
|||
End |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Hopper assembler: |
|||
Este mensaje será purgado! |
|||
Hopper Jambo formal syntax: |
|||
Este mensaje será purgado! |
|||
Hopper Jambo Natural syntax: |
|||
Este mensaje será purgado! |
|||
</pre> |
|||
=={{header|APL}}== |
|||
APL has a built-in function <tt>~</tt> ('without') that removes elements from a vector. Because a string is just |
|||
a character vector, this can be used to remove characters from a string. |
|||
<syntaxhighlight lang="apl">'She was a soul stripper. She took my heart!' ~ 'aei'</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|AppleScript}}== |
|||
===Using text item delimiters=== |
|||
{{works with|AppleScript|Mac OS X 10.6}} |
|||
<syntaxhighlight lang="applescript">stripChar("She was a soul stripper. She took my heart!", "aei") |
|||
on stripChar(str, chrs) |
|||
tell AppleScript |
|||
set oldTIDs to text item delimiters |
|||
set text item delimiters to characters of chrs |
|||
set TIs to text items of str |
|||
set text item delimiters to "" |
|||
set str to TIs as string |
|||
set text item delimiters to oldTIDs |
|||
end tell |
|||
return str |
|||
end stripChar</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
"Sh ws soul strppr. Sh took my hrt!" |
|||
</pre> |
|||
===By functional composition=== |
|||
====Without regex==== |
|||
{{Trans|Haskell}} |
|||
(Following the Haskell contribution in reversing the argument order to the sequence more probable in a context of potential currying or partial application). |
|||
<syntaxhighlight lang="applescript">-- stripChars :: String -> String -> String |
|||
on stripChars(needles, haystack) |
|||
script notNeedles |
|||
on |λ|(x) |
|||
needles does not contain x |
|||
end |λ| |
|||
end script |
|||
intercalate("", filter(notNeedles, haystack)) |
|||
end stripChars |
|||
--------------------------- TEST ------------------------- |
|||
on run |
|||
stripChars("aei", "She was a soul stripper. She took my heart!") |
|||
--> "Sh ws soul strppr. Sh took my hrt!" |
|||
end run |
|||
-------------------- GENERIC FUNCTIONS ------------------- |
|||
-- filter :: (a -> Bool) -> [a] -> [a] |
|||
on filter(f, xs) |
|||
tell mReturn(f) |
|||
set lst to {} |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to item i of xs |
|||
if |λ|(v, i, xs) then set end of lst to v |
|||
end repeat |
|||
return lst |
|||
end tell |
|||
end filter |
|||
-- intercalate :: Text -> [Text] -> Text |
|||
on intercalate(strText, lstText) |
|||
set {dlm, my text item delimiters} to {my text item delimiters, strText} |
|||
set strJoined to lstText as text |
|||
set my text item delimiters to dlm |
|||
return strJoined |
|||
end intercalate |
|||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- mReturn :: Handler -> Script |
|||
on mReturn(f) |
|||
if class of f is script then |
|||
f |
|||
else |
|||
script |
|||
property |λ| : f |
|||
end script |
|||
end if |
|||
end mReturn</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>"Sh ws soul strppr. Sh took my hrt!"</pre> |
|||
====With regex==== |
|||
OS X Yosemite onwards – importing the Foundation classes to use NSRegularExpression |
|||
<syntaxhighlight lang="applescript">use framework "Foundation" |
|||
--------- STRIP A SET OF CHARACTERS FROM A STRING -------- |
|||
-- stripChars :: String -> String -> String |
|||
on stripChars(needles, haystack) |
|||
intercalate("", ¬ |
|||
splitRegex("[" & needles & "]", haystack)) |
|||
end stripChars |
|||
--------------------------- TEST ------------------------- |
|||
on run |
|||
stripChars("aei", "She was a soul stripper. She took my heart!") |
|||
--> "Sh ws soul strppr. Sh took my hrt!" |
|||
end run |
|||
-------------------- GENERIC FUNCTIONS ------------------- |
|||
-- splitRegex :: RegexPattern -> String -> [String] |
|||
on splitRegex(strRegex, str) |
|||
set lstMatches to regexMatches(strRegex, str) |
|||
if length of lstMatches > 0 then |
|||
script preceding |
|||
on |λ|(a, x) |
|||
set iFrom to start of a |
|||
set iLocn to (location of x) |
|||
if iLocn > iFrom then |
|||
set strPart to text (iFrom + 1) thru iLocn of str |
|||
else |
|||
set strPart to "" |
|||
end if |
|||
{parts:parts of a & strPart, start:iLocn + (length of x) - 1} |
|||
end |λ| |
|||
end script |
|||
set recLast to foldl(preceding, {parts:[], start:0}, lstMatches) |
|||
set iFinal to start of recLast |
|||
if iFinal < length of str then |
|||
parts of recLast & text (iFinal + 1) thru -1 of str |
|||
else |
|||
parts of recLast & "" |
|||
end if |
|||
else |
|||
{str} |
|||
end if |
|||
end splitRegex |
|||
-- regexMatches :: RegexPattern -> String -> [{location:Int, length:Int}] |
|||
on regexMatches(strRegex, str) |
|||
set ca to current application |
|||
set oRgx to ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬ |
|||
options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) |error|:(missing value) |
|||
set oString to ca's NSString's stringWithString:str |
|||
set oMatches to oRgx's matchesInString:oString options:0 range:{location:0, |length|:oString's |length|()} |
|||
set lstMatches to {} |
|||
set lng to count of oMatches |
|||
repeat with i from 1 to lng |
|||
set end of lstMatches to range() of item i of oMatches |
|||
end repeat |
|||
lstMatches |
|||
end regexMatches |
|||
-- foldl :: (a -> b -> a) -> a -> [b] -> a |
|||
on foldl(f, startValue, xs) |
|||
tell mReturn(f) |
|||
set v to startValue |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to |λ|(v, item i of xs, i, xs) |
|||
end repeat |
|||
return v |
|||
end tell |
|||
end foldl |
|||
-- intercalate :: Text -> [Text] -> Text |
|||
on intercalate(strText, lstText) |
|||
set {dlm, my text item delimiters} to {my text item delimiters, strText} |
|||
set strJoined to lstText as text |
|||
set my text item delimiters to dlm |
|||
return strJoined |
|||
end intercalate |
|||
-- Lift 2nd class handler function into 1st class script wrapper |
|||
-- mReturn :: Handler -> Script |
|||
on mReturn(f) |
|||
if class of f is script then |
|||
f |
|||
else |
|||
script |
|||
property |λ| : f |
|||
end script |
|||
end if |
|||
end mReturn</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>"Sh ws soul strppr. Sh took my hrt!"</pre> |
|||
=={{header|Applesoft BASIC}}== |
|||
<syntaxhighlight lang="basic">100 LET S$ = "SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART!" |
|||
110 LET RM$ = "AEI" |
|||
120 GOSUB 200STRIPCHARS |
|||
130 PRINT SC$ |
|||
190 END |
|||
200 REM |
|||
210 REM STRIPCHARS |
|||
220 REM |
|||
230 LET SC$ = "" |
|||
240 LET SL = LEN (S$) |
|||
250 IF SL = 0 THEN RETURN |
|||
260 FOR SI = 1 TO SL |
|||
270 LET SM$ = MID$ (S$,SI,1) |
|||
280 FOR SJ = 1 TO LEN (RM$) |
|||
290 LET SR$ = MID$ (RM$,SJ,1) |
|||
300 LET ST = SR$ < > SM$ |
|||
310 IF ST THEN NEXT SJ |
|||
320 IF ST THEN SC$ = SC$ + SM$ |
|||
330 NEXT SI |
|||
340 RETURN |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>SH WS SOUL STRPPR. SH TOOK MY HRT!</pre> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">stripChars: function [str, chars]-> |
|||
join select split str => [not? in? & split chars] |
|||
print stripChars "She was a soul stripper. She took my heart!" "aei"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Asymptote}}== |
|||
<syntaxhighlight lang="asymptote">string text = "She was a soul stripper. She took my heart!"; |
|||
string[][] remove = {{"a",""},{"e",""},{"i",""}}; |
|||
for(var i : remove) |
|||
text = replace(text, remove); |
|||
} |
|||
write(text);</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
|||
<syntaxhighlight lang="autohotkey">MsgBox % stripchars("She was a soul stripper. She took my heart!","aei") |
|||
StripChars(string, charsToStrip){ |
|||
Loop Parse, charsToStrip |
|||
StringReplace, string, string, % A_LoopField, , All |
|||
return string |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|AWK}}== |
|||
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
|||
BEGIN { |
|||
x = "She was a soul stripper. She took my heart!"; |
|||
print x; |
|||
gsub(/[aei]/,"",x); |
|||
print x; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>She was a soul stripper. She took my heart! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|BaCon}}== |
|||
<syntaxhighlight lang="bacon">text$ = "She was a soul stripper. She took my heart!" |
|||
PRINT text$ |
|||
PRINT EXTRACT$(text$, "[aei]", TRUE) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>She was a soul stripper. She took my heart! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|BASIC}}== |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic">DECLARE FUNCTION stripchars$(src AS STRING, remove AS STRING) |
|||
PRINT stripchars$("She was a soul stripper. She took my heart!", "aei") |
|||
FUNCTION stripchars$(src AS STRING, remove AS STRING) |
|||
DIM l0 AS LONG, t AS LONG, s AS STRING |
|||
s = src |
|||
FOR l0 = 1 TO LEN(remove) |
|||
DO |
|||
t = INSTR(s, MID$(remove, l0, 1)) |
|||
IF t THEN |
|||
s = LEFT$(s, t - 1) + MID$(s, t + 1) |
|||
ELSE |
|||
EXIT DO |
|||
END IF |
|||
LOOP |
|||
NEXT |
|||
stripchars$ = s |
|||
END FUNCTION</syntaxhighlight> |
|||
{{out}} |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
{{trans|BASIC}} |
|||
<syntaxhighlight lang="qbasic">100 cls |
|||
110 print stripchars$("She was a soul stripper. She took my heart!","aei") |
|||
120 sub stripchars$(src$,remove$) |
|||
130 s$ = src$ |
|||
140 for l0 = 1 to len(remove$) |
|||
150 do |
|||
160 t = instr(s$,mid$(remove$,l0,1)) |
|||
170 if t then |
|||
180 s$ = left$(s$,t-1)+mid$(s$,t+1) |
|||
190 else |
|||
200 exit do |
|||
210 endif |
|||
220 loop |
|||
230 next |
|||
240 stripchars$ = s$ |
|||
250 end sub |
|||
260 end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 PROGRAM "Stripchr.bas" |
|||
110 PRINT STRIPCHARS$("She was a soul stripper. She took my heart!","aei") |
|||
120 DEF STRIPCHARS$(SRC$,REMOVE$) |
|||
130 LET T$="" |
|||
140 FOR I=1 TO LEN(SRC$) |
|||
150 LET L=0 |
|||
160 FOR J=1 TO LEN(REMOVE$) |
|||
170 IF SRC$(I)=REMOVE$(J) THEN LET L=1:EXIT FOR |
|||
180 NEXT |
|||
190 IF L=0 THEN LET T$=T$&SRC$(I) |
|||
200 NEXT |
|||
210 LET STRIPCHARS$=T$ |
|||
220 END DEF</syntaxhighlight> |
|||
==={{header|Sinclair ZX81 BASIC}}=== |
|||
Works with 1k of RAM. Since the ZX81 character set includes neither lower case nor <tt>!</tt>, the test string is not quite identical to the one suggested in the specification. |
|||
<syntaxhighlight lang="basic"> 10 LET A$="SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART." |
|||
20 LET B$="AEI" |
|||
30 GOSUB 60 |
|||
40 PRINT C$ |
|||
50 STOP |
|||
60 LET C$="" |
|||
70 FOR I=1 TO LEN A$ |
|||
80 LET J=1 |
|||
90 IF A$(I)=B$(J) THEN GOTO 130 |
|||
100 LET J=J+1 |
|||
110 IF J<=LEN B$ THEN GOTO 90 |
|||
120 LET C$=C$+A$(I) |
|||
130 NEXT I |
|||
140 RETURN</syntaxhighlight> |
|||
{{out}} |
|||
<pre>SH WS SOUL STRPPR. SH TOOK MY HRT.</pre> |
|||
See also: [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]] |
|||
=={{header|BASIC256}}== |
|||
<syntaxhighlight lang="basic256">function stripchars(texto, remove) |
|||
s = texto |
|||
for i = 1 to length(remove) |
|||
s = replace(s, mid(remove, i, 1), "", true) #true se puede omitir |
|||
next i |
|||
return s |
|||
end function |
|||
print stripchars("She was a soul stripper. She took my heart!", "aei")</syntaxhighlight> |
|||
=={{header|BBC BASIC}}== |
|||
<syntaxhighlight lang="bbcbasic"> PRINT FNstripchars("She was a soul stripper. She took my heart!", "aei") |
|||
END |
|||
DEF FNstripchars(A$, S$) |
|||
LOCAL I%, C%, C$ |
|||
FOR I% = 1 TO LEN(S$) |
|||
C$ = MID$(S$, I%, 1) |
|||
REPEAT |
|||
C% = INSTR(A$, C$) |
|||
IF C% A$ = LEFT$(A$, C%-1) + MID$(A$, C%+1) |
|||
UNTIL C% = 0 |
|||
NEXT |
|||
= A$</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|BCPL}}== |
|||
<syntaxhighlight lang="bcpl">get "libhdr" |
|||
let contains(str, chr) = valof |
|||
$( for i = 1 to str%0 |
|||
if str%i = chr resultis true |
|||
resultis false |
|||
$) |
|||
let stripchars(str, chars, buf) = valof |
|||
$( buf%0 := 0 |
|||
for i = 1 to str%0 |
|||
if ~contains(chars, str%i) |
|||
$( buf%0 := buf%0 + 1 |
|||
buf%(buf%0) := str%i |
|||
$) |
|||
resultis buf |
|||
$) |
|||
let start() be |
|||
$( let buf = vec 127 |
|||
writef("%S*N", |
|||
stripchars("She was a soul stripper. She took my heart!", |
|||
"aei", |
|||
buf)) |
|||
$)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|BQN}}== |
|||
The key function here is set difference, which is <code>(¬∘∊/⊣)</code>. |
|||
<syntaxhighlight lang="bqn"> StripChars ← (¬∘∊/⊣) |
|||
¬∘∊/⊣ |
|||
"She was a soul stripper. She took my heart!" StripChars "aei" |
|||
"Sh ws soul strppr. Sh took my hrt!"</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
|||
This solution handles Unicode (utf-8) characters. Optimizations are: (1) the <code>chars</code> string is hard-coded into the pattern before the pattern is used in the match expression, (2) the output characters are stacked (cheap) rather than appended (expensive). The result string is obtained by stringizing the stack and reversing. To make multibyte characters survive, they are reversed before being put onto the stack. A problem is that this code is negligent of diacritical marks. |
|||
<syntaxhighlight lang="bracmat">( ( strip |
|||
= string chars s pat |
|||
. !arg:(?string.?chars) |
|||
& :?s |
|||
& |
|||
' ( ? |
|||
( % |
|||
: [%( utf$!sjt |
|||
& ( @($chars:? !sjt ?) |
|||
| rev$!sjt !s:?s |
|||
) |
|||
& ~ |
|||
) |
|||
) |
|||
? |
|||
) |
|||
: (=?pat) |
|||
& @(!string:!pat) |
|||
| rev$(str$!s) |
|||
) |
|||
& out |
|||
$ (strip$("Аппетит приходит во время еды".веп) |
|||
);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Атит риходит о рмя ды</pre> |
|||
=={{header|Burlesque}}== |
|||
<syntaxhighlight lang="burlesque"> |
|||
blsq ) "She was a soul stripper. She took my heart!"{"aei"\/~[n!}f[ |
|||
"Sh ws soul strppr. Sh took my hrt!" |
|||
</syntaxhighlight> |
|||
=={{header|C}}== |
|||
<syntaxhighlight lang="c">#include <string.h> |
|||
#include <stdio.h> |
|||
#include <stdlib.h> |
|||
/* removes all chars from string */ |
|||
char *strip_chars(const char *string, const char *chars) |
|||
{ |
|||
char * newstr = malloc(strlen(string) + 1); |
|||
int counter = 0; |
|||
for ( ; *string; string++) { |
|||
if (!strchr(chars, *string)) { |
|||
newstr[ counter ] = *string; |
|||
++ counter; |
|||
} |
|||
} |
|||
newstr[counter] = 0; |
|||
return newstr; |
|||
} |
|||
int main(void) |
|||
{ |
|||
char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); |
|||
printf("%s\n", new); |
|||
free(new); |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
{{out|Result}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
===With table lookup=== |
|||
<syntaxhighlight lang="c">#include <stdio.h> |
|||
#include <stdlib.h> |
|||
#include <string.h> |
|||
char *strip(const char * str, const char *pat) |
|||
{ |
|||
/* char replacement is typically done with lookup tables if |
|||
* the replacement set can be large: it turns O(m n) into |
|||
* O(m + n). |
|||
* If same replacement pattern is going to be applied to many |
|||
* strings, it's better to build a table beforehand and reuse it. |
|||
* If charset is big like unicode, table needs to be implemented |
|||
* more efficiently, say using bit field or hash table -- it |
|||
* all depends on the application. |
|||
*/ |
|||
int i = 0, tbl[128] = {0}; |
|||
while (*pat != '\0') tbl[(int)*(pat++)] = 1; |
|||
char *ret = malloc(strlen(str) + 1); |
|||
do { |
|||
if (!tbl[(int)*str]) |
|||
ret[i++] = *str; |
|||
} while (*(str++) != '\0'); |
|||
/* assuming realloc is efficient and succeeds; if not, we could |
|||
* do a two-pass, count first, alloc and strip second |
|||
*/ |
|||
return realloc(ret, i); |
|||
} |
|||
int main() |
|||
{ |
|||
char * x = strip("She was a soul stripper. She took my heart!", "aei"); |
|||
printf(x); |
|||
free(x); |
|||
return 0; |
|||
}</syntaxhighlight>Output same as above. |
|||
==={{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, c = ".$%#\tEste@@@ mensaje será purgado!$$$", set = "$%#@.\t"; |
|||
Stack{ |
|||
Store ( r, Char_del( Upper( c ), set ) ); |
|||
}Stack_off |
|||
Print "Original = [%s]\nChar deleted = [%s]\n", c, r; |
|||
Free secure r,c,set; |
|||
End |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Original = [.$%# Este@@@ mensaje será purgado!$$$] |
|||
Char deleted = [ESTE MENSAJE SERÁ PURGADO!] |
|||
</pre> |
|||
=={{header|C sharp}}== |
|||
<syntaxhighlight lang="csharp">using System; |
|||
public static string RemoveCharactersFromString(string testString, string removeChars) |
|||
{ |
|||
char[] charAry = removeChars.ToCharArray(); |
|||
string returnString = testString; |
|||
foreach (char c in charAry) |
|||
{ |
|||
while (returnString.IndexOf(c) > -1) |
|||
{ |
|||
returnString = returnString.Remove(returnString.IndexOf(c), 1); |
|||
} |
|||
} |
|||
return returnString; |
|||
}</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="c sharp"> |
|||
using System; |
|||
class Program |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
string testString = "She was a soul stripper. She took my heart!"; |
|||
string removeChars = "aei"; |
|||
Console.WriteLine(RemoveCharactersFromString(testString, removeChars)); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
Using <code>Regex</code>: |
|||
<syntaxhighlight lang="c sharp"> |
|||
using System; |
|||
using System.Text.RegularExpressions; |
|||
private static string RegexRemoveCharactersFromString(string testString, string removeChars) |
|||
{ |
|||
string pattern = "[" + removeChars + "]"; |
|||
return Regex.Replace(testString, pattern, ""); |
|||
}</syntaxhighlight> |
|||
<b>Alternative version</b> using <code>System.Span<T></code>: |
|||
<syntaxhighlight lang="csharp">using System; |
|||
public static System.ReadOnlySpan<T> RemoveItems<T>(System.Span<T> toStrip, System.ReadOnlySpan<T> toRemove) |
|||
where T : System.IEquatable<T> |
|||
{ |
|||
var toIndex = toStrip.Length; |
|||
for (var fromIndex = toIndex - 1; fromIndex >= 0; fromIndex--) |
|||
if (toStrip[fromIndex] is var item && !toRemove.Contains(item)) |
|||
toStrip[--toIndex] = item; |
|||
return toStrip.Slice(toIndex); |
|||
}</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="csharp">using System; |
|||
class Program |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
var stripString = "She was a soul stripper. She took my heart!"; |
|||
var removeString = "aei"; |
|||
System.Console.WriteLine(RemoveItems<char>(stripString.ToCharArray(), removeString).ToString()); |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|C++}}== |
|||
{{works with|C++11}} |
|||
<syntaxhighlight lang="cpp">#include <algorithm> |
|||
#include <iostream> |
|||
#include <string> |
|||
std::string stripchars(std::string str, const std::string &chars) |
|||
{ |
|||
str.erase( |
|||
std::remove_if(str.begin(), str.end(), [&](char c){ |
|||
return chars.find(c) != std::string::npos; |
|||
}), |
|||
str.end() |
|||
); |
|||
return str; |
|||
} |
|||
int main() |
|||
{ |
|||
std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Clojure}}== |
|||
<syntaxhighlight lang="clojure">(defn strip [coll chars] |
|||
(apply str (remove #((set chars) %) coll))) |
|||
(strip "She was a soul stripper. She took my heart!" "aei") |
|||
;; => "Sh ws soul strppr. Sh took my hrt!"</syntaxhighlight> |
|||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">stripchars = proc (input, chars: string) returns (string) |
|||
result: array[char] := array[char]$[] |
|||
for c: char in string$chars(input) do |
|||
if string$indexc(c, chars) = 0 then |
|||
array[char]$addh(result, c) |
|||
end |
|||
end |
|||
return(string$ac2s(result)) |
|||
end stripchars |
|||
start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
stream$putl(po, |
|||
stripchars("She was a soul stripper. She took my heart!", "aei")) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|COBOL}}== |
|||
This function takes the two arguments as specified in the task. However, the result will be returned in the string that had the characters stripped from it, and the string containing the characters to strip must be null-terminated (otherwise, a table would have to be used instead). |
|||
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. Strip-Chars. |
|||
DATA DIVISION. |
|||
WORKING-STORAGE SECTION. |
|||
01 Str-Size CONSTANT 128. |
|||
LOCAL-STORAGE SECTION. |
|||
01 I PIC 999. |
|||
01 Str-Pos PIC 999. |
|||
01 Offset PIC 999. |
|||
01 New-Pos PIC 999. |
|||
01 Str-End PIC 999. |
|||
LINKAGE SECTION. |
|||
01 Str PIC X(Str-Size). |
|||
01 Chars-To-Replace PIC X(256). |
|||
PROCEDURE DIVISION USING Str BY VALUE Chars-To-Replace. |
|||
Main. |
|||
PERFORM VARYING I FROM 1 BY 1 |
|||
UNTIL Chars-To-Replace (I:1) = X"00" |
|||
MOVE ZERO TO Offset |
|||
* *> Overwrite the characters to remove by left-shifting |
|||
* *> following characters over them. |
|||
PERFORM VARYING Str-Pos FROM 1 BY 1 |
|||
UNTIL Str-Size < Str-Pos |
|||
IF Str (Str-Pos:1) = Chars-To-Replace (I:1) |
|||
ADD 1 TO Offset |
|||
ELSE IF Offset NOT = ZERO |
|||
COMPUTE New-Pos = Str-Pos - Offset |
|||
MOVE Str (Str-Pos:1) TO Str (New-Pos:1) |
|||
END-IF |
|||
END-PERFORM |
|||
* *> Move spaces to characters at the end that have been |
|||
* *> shifted over. |
|||
COMPUTE Str-End = Str-Size - Offset |
|||
MOVE SPACES TO Str (Str-End:Offset) |
|||
END-PERFORM |
|||
GOBACK |
|||
.</syntaxhighlight> |
|||
=={{header|ColdFusion}}== |
|||
<syntaxhighlight lang="cfm"> |
|||
<Cfset theString = 'She was a soul stripper. She took my heart!'> |
|||
<Cfset theStrip = 'aei'> |
|||
<Cfloop from="1" to="#len(theStrip)#" index="i"> |
|||
<cfset theString = replace(theString, Mid(theStrip, i, 1), '', 'all')> |
|||
</Cfloop> |
|||
<Cfoutput>#theString#</Cfoutput> |
|||
</syntaxhighlight> |
|||
=={{header|Common Lisp}}== |
|||
<syntaxhighlight lang="lisp">(defun strip-chars (str chars) |
|||
(remove-if (lambda (ch) (find ch chars)) str)) |
|||
(strip-chars "She was a soul stripper. She took my heart!" "aei") |
|||
;; => "Sh ws soul strppr. Sh took my hrt!" |
|||
;; strip whitespace: |
|||
(string-trim |
|||
'(#\Space #\Newline #\Backspace #\Tab |
|||
#\Linefeed #\Page #\Return #\Rubout) |
|||
" A string ") |
|||
;; => "A string" |
|||
</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
This example shows both the functional and regex solutions. |
|||
<lang d>import std.stdio, std.string; |
|||
<syntaxhighlight lang="d">import std.stdio; |
|||
string stripchars(string s, string chars) { |
|||
import std.algorithm; |
|||
import std.conv; |
|||
return s.filter!(c => !chars.count(c)).to!string; |
|||
} |
|||
string stripchars2(string s, string chars) { |
|||
import std.regex; |
|||
return replaceAll(s, regex("[" ~ chars ~ "]"), ""); |
|||
} |
|||
void main() { |
void main() { |
||
string s = "She was a soul stripper. She took my heart!"; |
|||
string chars = "aei"; |
|||
auto ss = "Sh ws soul strppr. Sh took my hrt!"; |
|||
assert(s.removechars("aei") == ss); |
|||
writeln(stripchars(s, chars)); |
|||
}</lang> |
|||
writeln(stripchars2(s, chars)); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt! |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Delphi}}== |
|||
<syntaxhighlight lang="delphi">program StripCharacters; |
|||
{$APPTYPE CONSOLE} |
|||
uses SysUtils; |
|||
function StripChars(const aSrc, aCharsToStrip: string): string; |
|||
var |
|||
c: Char; |
|||
begin |
|||
Result := aSrc; |
|||
for c in aCharsToStrip do |
|||
Result := StringReplace(Result, c, '', [rfReplaceAll, rfIgnoreCase]); |
|||
end; |
|||
const |
|||
TEST_STRING = 'She was a soul stripper. She took my heart!'; |
|||
begin |
|||
Writeln(TEST_STRING); |
|||
Writeln(StripChars(TEST_STRING, 'aei')); |
|||
end.</syntaxhighlight> |
|||
=={{header|Draco}}== |
|||
<syntaxhighlight lang="draco">\util.g |
|||
proc nonrec stripchars(*char str, chars, outbuf) *char: |
|||
channel input text ch_in; |
|||
channel output text ch_out; |
|||
[2]char cur = ('\e', '\e'); |
|||
open(ch_in, str); |
|||
open(ch_out, outbuf); |
|||
while read(ch_in; cur[0]) do |
|||
if CharsIndex(chars, &cur[0]) = -1 then |
|||
write(ch_out; cur[0]) |
|||
fi |
|||
od; |
|||
close(ch_in); |
|||
close(ch_out); |
|||
outbuf |
|||
corp |
|||
proc nonrec main() void: |
|||
[128]char buf; |
|||
writeln( |
|||
stripchars("She was a soul stripper. She took my heart!", |
|||
"aei", &buf[0])) |
|||
corp</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|EasyLang}}== |
|||
<syntaxhighlight> |
|||
func$ strip s$ del$ . |
|||
for c$ in strchars s$ |
|||
if strpos del$ c$ <> 0 |
|||
c$ = "" |
|||
. |
|||
r$ &= c$ |
|||
. |
|||
return r$ |
|||
. |
|||
print strip "She was a soul stripper. She took my heart!" "aei" |
|||
</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
;; using regexp /[chars]/g |
|||
(define (strip-chars string chars) |
|||
(string-replace string (string-append "/[" chars "]/g") "")) |
|||
(strip-chars "She was a soul stripper. She took my heart!" "aei") |
|||
→ "Sh ws soul strppr. Sh took my hrt!" |
|||
</syntaxhighlight> |
|||
=={{header|Elena}}== |
|||
ELENA 4.x : |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
import extensions'text; |
|||
import system'routines; |
|||
public program() |
|||
{ |
|||
var testString := "She was a soul stripper. She took my heart!"; |
|||
var removeChars := "aei"; |
|||
console.printLine(testString.filterBy::(ch => removeChars.indexOf(0, ch) == -1).summarize(new StringWriter())) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Elixir}}== |
|||
The easiest solution would be to use replace from the String module, which takes a Regex. |
|||
<syntaxhighlight lang="elixir">str = "She was a soul stripper. She took my heart!" |
|||
String.replace(str, ~r/[aei]/, "") |
|||
# => Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
To get the desired interface, we just have to dynamically construct the Regex: |
|||
<syntaxhighlight lang="elixir">defmodule RC do |
|||
def stripchars(str, chars) do |
|||
String.replace(str, ~r/[#{chars}]/, "") |
|||
end |
|||
end |
|||
str = "She was a soul stripper. She took my heart!" |
|||
RC.stripchars(str, "aei") |
|||
# => Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
=={{header|Emacs Lisp}}== |
|||
<syntaxhighlight lang="lisp"> |
|||
(defun stripchars (s chars) |
|||
(seq-into |
|||
(seq-filter (lambda (x) (not (seq-contains chars x))) s) |
|||
'string)) |
|||
(stripchars "She was a soul stripper. She took my heart!" "aei") |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
"Sh ws soul strppr. Sh took my hrt!" |
|||
</pre> |
|||
=={{header|Erlang}}== |
|||
The function is created in the shell. A module would be over engineering. |
|||
{{out}} |
|||
<pre> |
|||
4> F = fun(To_stripp, Strip_with) -> lists:filter( fun(C) -> not lists:member(C, Strip_with) end, To_stripp ) end. |
|||
#Fun<erl_eval.12.111823515> |
|||
5> F("She was a soul stripper. She took my heart!", "aei"). |
|||
"Sh ws soul strppr. Sh took my hrt!" |
|||
</pre> |
|||
=={{header|Euphoria}}== |
|||
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}} |
|||
The includes use Euphoria 4 standard library files. |
|||
A sequence called <tt>originalString</tt> holds the text to be converted. |
|||
The <code>puts</code> function is for console output. |
|||
The work of this task is done by the <code>transmute</code> function; this function takes parameters separated by commas. Here it uses 3 parameters, up to 5, the other two are optional and aren't put in this time. |
|||
The <code>transmute</code> function's usage and examples can be searched for in the official Euphoria 4.0.0+ manual. Euphoria object identifiers (names) are case sensitive but don't need to be in a particular case to be recognized as an object type. |
|||
<syntaxhighlight lang="euphoria">include std\sequence.e |
|||
include std\console.e |
|||
sequence originalString = "She was a soul stripper. She took my heart!" |
|||
puts(1,"Before : " & originalString & "\n") |
|||
originalString = transmute(originalString, {{} , "a", "e", "i"}, {{} , "", "", ""}) |
|||
puts(1,"After : " & originalString & "\n") |
|||
any_key()</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Before : She was a soul stripper. She took my heart! |
|||
After : Sh ws soul strppr. Sh took my hrt! |
|||
Press Any Key to continue...</pre> |
|||
=={{header|Excel}}== |
|||
===LAMBDA=== |
|||
Binding the name '''exceptChars''' to the following lambda expression in the Name Manager of the Excel WorkBook: |
|||
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function]) |
|||
{{Works with|Office 365 betas 2021}} |
|||
<syntaxhighlight lang="lisp">exceptChars |
|||
=LAMBDA(excluded, |
|||
LAMBDA(src, |
|||
CONCAT( |
|||
FILTERP( |
|||
LAMBDA(c, |
|||
ISERROR( |
|||
FIND(c, excluded, 1) |
|||
) |
|||
) |
|||
)( |
|||
CHARSROW(src) |
|||
) |
|||
) |
|||
) |
|||
)</syntaxhighlight> |
|||
and also assuming the following generic bindings in the Name Manager for the WorkBook: |
|||
<syntaxhighlight lang="lisp">CHARSROW |
|||
=LAMBDA(s, |
|||
MID(s, |
|||
SEQUENCE(1, LEN(s), 1, 1), |
|||
1 |
|||
) |
|||
) |
|||
FILTERP |
|||
=LAMBDA(p, |
|||
LAMBDA(xs, |
|||
FILTER(xs, p(xs)) |
|||
) |
|||
)</syntaxhighlight> |
|||
{{Out}} |
|||
{| class="wikitable" |
|||
|- |
|||
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx |
|||
! colspan="2" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=exceptChars(A2)(B1) |
|||
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;" |
|||
| |
|||
| A |
|||
| B |
|||
|- |
|||
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1 |
|||
| |
|||
| She was a soul stripper. She took my heart! |
|||
|- |
|||
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2 |
|||
| aei |
|||
| style="background-color:#cbcefb" | Sh ws soul strppr. Sh took my hrt! |
|||
|} |
|||
=={{header|F_Sharp|F#}}== |
|||
<syntaxhighlight lang="fsharp"> |
|||
let stripChars text (chars:string) = |
|||
Seq.fold ( |
|||
fun (s:string) c -> s.Replace(c.ToString(),"") |
|||
) text chars |
|||
printfn "%s" (stripChars "She was a soul stripper. She took my heart!" "aei") |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
</pre> |
|||
=={{header|Factor}}== |
|||
<syntaxhighlight lang="factor">without</syntaxhighlight> |
|||
Example: |
|||
<syntaxhighlight lang="factor">USE: sets |
|||
"She was a soul stripper. She took my heart!" "aei" without print</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Forth}}== |
|||
Forth is a low level language that is extended to solve your problem. |
|||
Here we add APPEND-CHAR to the language and use it built the new string |
|||
character by character in a memory buffer called PAD. PAD is a standard Forth word. |
|||
SCAN is common in most Forth systems and is typically coded in Forth assembler |
|||
<syntaxhighlight lang="forth">: append-char ( char str -- ) dup >r count dup 1+ r> c! + c! ; \ append char to a counted string |
|||
: strippers ( -- addr len) s" aeiAEI" ; \ a string literal returns addr and length |
|||
: stripchars ( addr1 len1 addr2 len2 -- PAD len ) |
|||
0 PAD c! \ clear the PAD buffer |
|||
bounds \ calc loop limits for addr2 |
|||
DO |
|||
2dup I C@ ( -- addr1 len1 addr1 len1 char) |
|||
scan nip 0= \ scan for char in addr1, test for zero |
|||
IF \ if stack = true (ie. NOT found) |
|||
I c@ PAD append-char \ fetch addr2 char, append to PAD |
|||
THEN \ ...then ... continue the loop |
|||
LOOP |
|||
2drop \ we don't need STRIPPERS now |
|||
PAD count ; \ return PAD address and length |
|||
</syntaxhighlight> |
|||
Test at the forth console |
|||
<pre>strippers s" She was a soul stripper. She took my heart!" stripchars cr type |
|||
Sh ws soul strppr. Sh took my hrt! ok |
|||
</pre> |
|||
===Shorter version, using ]] [[ macros=== |
|||
This shorter version removes creating a new string and prints the "stripped" string immediately. |
|||
The macro called '?exit' speeds up the '.stripped' print loop by compiling its code inside the loop. |
|||
<syntaxhighlight lang="forth">: ?exit ( c1 c2 -- ) ]] = if drop unloop exit then [[ ; immediate |
|||
: .stripped ( a u c -- ) -rot bounds ?do dup i c@ ?exit loop emit ; |
|||
: stripchars ( a1 u1 a2 u2 -- ) bounds ?do 2dup i c@ .stripped loop 2drop ; |
|||
: "aei" s" aei" ; |
|||
\ usage: "aei" s" She was a soul stripper. She took my heart!" stripchars</syntaxhighlight> |
|||
=={{header|Fortran}}== |
|||
<syntaxhighlight lang="fortran">elemental subroutine strip(string,set) |
|||
character(len=*), intent(inout) :: string |
|||
character(len=*), intent(in) :: set |
|||
integer :: old, new, stride |
|||
old = 1; new = 1 |
|||
do |
|||
stride = scan( string( old : ), set ) |
|||
if ( stride > 0 ) then |
|||
string( new : new+stride-2 ) = string( old : old+stride-2 ) |
|||
old = old+stride |
|||
new = new+stride-1 |
|||
else |
|||
string( new : ) = string( old : ) |
|||
return |
|||
end if |
|||
end do |
|||
end subroutine strip</syntaxhighlight>Note: Since strip is an elemental subroutine, it can be called with arrays of strings as well. |
|||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Function stripChars(s As Const String, chars As Const String) As String |
|||
If s = "" Then Return "" |
|||
Dim count As Integer = 0 |
|||
Dim strip(0 To Len(s) - 1) As Boolean |
|||
For i As Integer = 0 To Len(s) - 1 |
|||
For j As Integer = 0 To Len(chars) - 1 |
|||
If s[i] = chars[j] Then |
|||
count += 1 |
|||
strip(i) = True |
|||
Exit For |
|||
End If |
|||
Next j |
|||
Next i |
|||
Dim buffer As String = Space(Len(s) - count) |
|||
count = 0 |
|||
For i As Integer = 0 To Len(s) - 1 |
|||
If Not Strip(i) Then |
|||
buffer[count] = s[i] |
|||
count += 1 |
|||
End If |
|||
Next |
|||
Return buffer |
|||
End Function |
|||
Dim s As String = "She was a soul stripper. She took my heart!" |
|||
Dim chars As String = "aei" |
|||
Print stripChars(s, chars) |
|||
Print |
|||
Print "Press any key to quit" |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Frink}}== |
|||
<syntaxhighlight lang="frink">stripchars[str, remove] := |
|||
{ |
|||
set = toSet[chars[remove]] |
|||
return char[remove[char[str], {|c, set| set.contains[c]}, set]] |
|||
} |
|||
println[stripchars["She was a soul stripper. She took my heart!","aei"]] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Strip_a_set_of_characters_from_a_string}} |
|||
'''Solution''' |
|||
[[File:Fōrmulæ - Strip a set of characters from a string 01.png]] |
|||
'''Test case''' |
|||
[[File:Fōrmulæ - Strip a set of characters from a string 02.png]] |
|||
[[File:Fōrmulæ - Strip a set of characters from a string 03.png]] |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic">window 1, @"Strip a set of characters from a string" |
|||
local fn StringByStrippingCharacters( string as CFStringRef, chrs as CFStringRef ) as CFStringRef |
|||
end fn = fn ArrayComponentsJoinedByString( fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetWithCharactersInString( chrs ) ), @"" ) |
|||
CFStringRef string, chrs |
|||
string = @"She was a soul stripper. She took my heart!" |
|||
chrs = @"aei" |
|||
print string |
|||
print fn StringByStrippingCharacters( string, chrs ) |
|||
HandleEvents</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
She was a soul stripper. She took my heart! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=f199a8f7a56cf466e4a16c3fc71f6278 Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Print StripChars("She was a soul stripper. She took my heart!", "aei") |
|||
End |
|||
'_____________________________________________________________________ |
|||
Public Sub StripChars(sText As String, sRemove As String) As String |
|||
Dim siCount As Short |
|||
For siCount = 1 To Len(sRemove) |
|||
sText = Replace(sText, Mid(sRemove, siCount, 1), "") |
|||
Next |
|||
Return sText |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Go}}== |
|||
<syntaxhighlight lang="go">package main |
|||
import ( |
|||
"fmt" |
|||
"strings" |
|||
) |
|||
func stripchars(str, chr string) string { |
|||
return strings.Map(func(r rune) rune { |
|||
if strings.IndexRune(chr, r) < 0 { |
|||
return r |
|||
} |
|||
return -1 |
|||
}, str) |
|||
} |
|||
func main() { |
|||
fmt.Println(stripchars("She was a soul stripper. She took my heart!", |
|||
"aei")) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Groovy}}== |
|||
Solution: |
|||
<syntaxhighlight lang="groovy">def stripChars = { string, stripChars -> |
|||
def list = string as List |
|||
list.removeAll(stripChars as List) |
|||
list.join() |
|||
}</syntaxhighlight> |
|||
Test: |
|||
<syntaxhighlight lang="groovy">println (stripChars('She was a soul stripper. She took my heart!', 'aei'))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Haskell}}== |
|||
I decided to make the string the second argument and the characters the first argument, because it is more likely for someone to partially apply the characters to be stripped (making a function that strips certain characters), than the string. |
|||
<syntaxhighlight lang="haskell">stripChars :: String -> String -> String |
|||
stripChars = filter . flip notElem</syntaxhighlight> |
|||
{{out|Testing in GHCI}} |
|||
<pre>> stripChars "aei" "She was a soul stripper. She took my heart!" |
|||
"Sh ws soul strppr. Sh took my hrt!"</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
The following works in both languages: |
The following works in both languages: |
||
< |
<syntaxhighlight lang="unicon">procedure main(A) |
||
cs := \A[1] | 'aei' # argument is set of characters to strip |
cs := \A[1] | 'aei' # argument is set of characters to strip |
||
every write(stripChars(!&input, cs)) # strip all input lines |
every write(stripChars(!&input, cs)) # strip all input lines |
||
Line 22: | Line 1,710: | ||
procedure stripChars(s,cs) |
procedure stripChars(s,cs) |
||
ns := "" |
ns := "" |
||
s ? while ns ||:= (not pos(0), tab(upto(cs)|0)) do tab(many(cs |
s ? while ns ||:= (not pos(0), tab(upto(cs)|0)) do tab(many(cs)) |
||
return ns |
return ns |
||
end</ |
end</syntaxhighlight> |
||
{{out|Sample runs}} |
|||
Sample runs: |
|||
<pre>->strip |
<pre>->strip |
||
She was a soul stripper. She took my heart! |
She was a soul stripper. She took my heart! |
||
Line 36: | Line 1,723: | ||
rdvrks r nt trs. |
rdvrks r nt trs. |
||
-></pre> |
-></pre> |
||
=={{header|Insitux}}== |
|||
{{Trans|Clojure}} |
|||
<syntaxhighlight lang="insitux">(function strip from what |
|||
(remove (to-vec what) from)) |
|||
(strip "She was a soul stripper. She took my heart!" "aei") |
|||
;returns "Sh ws soul strppr. Sh took my hrt!"</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution:'''<br> |
'''Solution:'''<br> |
||
The dyadic primitive <code>-.</code> ([http://www.jsoftware.com/help/dictionary/d121.htm Less]) is probably the simplest way to solve this task. |
The dyadic primitive <code>-.</code> ([http://www.jsoftware.com/help/dictionary/d121.htm Less]) is probably the simplest way to solve this task. |
||
{{out|Example Usage}} |
|||
<syntaxhighlight lang="j"> 'She was a soul stripper. She took my heart!' -. 'aei' |
|||
Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
=={{header|Java}}== |
|||
'''Example Usage:''' |
|||
The most basic approach is to use the ''String.replace'' method. |
|||
<lang j> 'She was a soul stripper. She took my heart!' -. 'aei' |
|||
<syntaxhighlight lang="java"> |
|||
Sh ws soul strppr. Sh took my hrt!</lang> |
|||
String stripCharacters(String string, String characters) { |
|||
for (char character : characters.toCharArray()) |
|||
string = string.replace(String.valueOf(character), ""); |
|||
return string; |
|||
} |
|||
</syntaxhighlight> |
|||
You could also use a ''StringBuilder'' which provides a ''deleteCharAt'' method. |
|||
<syntaxhighlight lang="java"> |
|||
String stripCharacters(String string, String characters) { |
|||
StringBuilder stripped = new StringBuilder(string); |
|||
/* traversing the string backwards is necessary to avoid collision */ |
|||
for (int index = string.length() - 1; index >= 0; index--) { |
|||
if (characters.contains(String.valueOf(string.charAt(index)))) |
|||
stripped.deleteCharAt(index); |
|||
} |
|||
return stripped.toString(); |
|||
} |
|||
</syntaxhighlight> |
|||
You could use the ''String.replaceAll'' method, which takes a regular expression as it's first argument. |
|||
<syntaxhighlight lang="java"> |
|||
static String stripCharacters(String string, String characters) { |
|||
/* be sure to 'quote' the 'characters' to avoid pattern collision */ |
|||
characters = Pattern.quote(characters); |
|||
string = string.replaceAll("[%s]".formatted(characters), ""); |
|||
return string; |
|||
} |
|||
</syntaxhighlight> |
|||
These will all produce the following string. |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header| |
=={{header|JavaScript}}== |
||
===ES5=== |
|||
<lang ocaml>let stripchars s cs = |
|||
<syntaxhighlight lang="javascript">function stripchars(string, chars) { |
|||
return string.replace(RegExp('['+chars+']','g'), ''); |
|||
}</syntaxhighlight> |
|||
===ES6=== |
|||
Reversing the order of the arguments, to simplify any currying: |
|||
<syntaxhighlight lang="javascript">(() => { |
|||
'use strict'; |
|||
// stripChars :: String -> String -> String |
|||
const stripChars = (strNeedles, strHayStack) => |
|||
strHayStack.replace(RegExp(`[${strNeedles}]`, 'g'), ''); |
|||
// GENERIC FUNCTION |
|||
// curry :: ((a, b) -> c) -> a -> b -> c |
|||
const curry = f => a => b => f(a, b); |
|||
// TEST FUNCTION |
|||
const noAEI = curry(stripChars)('aeiAEI'); |
|||
// TEST |
|||
return noAEI('She was a soul stripper. She took my heart!'); |
|||
// 'Sh ws soul strppr. Sh took my hrt!' |
|||
})();</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>'Sh ws soul strppr. Sh took my hrt!'</pre> |
|||
Alternatively, we could also do this without a regex: |
|||
<syntaxhighlight lang="javascript">(() => { |
|||
'use strict'; |
|||
// stripChars :: String -> String -> String |
|||
const stripChars = (strNeedles, strHayStack) => |
|||
strHayStack.split('') |
|||
.filter(x => !elem(x, strNeedles)) |
|||
.join(''); |
|||
// GENERIC FUNCTIONS |
|||
// elem :: Eq a => a -> [a] -> Bool |
|||
const elem = (x, xs) => xs.indexOf(x) !== -1; |
|||
// curry :: ((a, b) -> c) -> a -> b -> c |
|||
const curry = f => a => b => f(a, b); |
|||
// TEST FUNCTION |
|||
const noAEI = curry(stripChars)('aeiAEI'); |
|||
// TEST |
|||
return noAEI('She was a soul stripper. She took my heart!'); |
|||
// 'Sh ws soul strppr. Sh took my hrt!' |
|||
})();</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>'Sh ws soul strppr. Sh took my hrt!'</pre> |
|||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">DEFINE stripchars == [in not] cons filter. |
|||
"She was a soul stripper. She took my heart!" "aei" stripchars.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>"Sh ws soul strppr. Sh took my hrt!"</pre> |
|||
=={{header|jq}}== |
|||
<syntaxhighlight lang="jq">def stripchars(string; banish): |
|||
(string | explode) - (banish | explode) | implode;</syntaxhighlight> |
|||
'''Note''': In jq, it would be more idiomatic to define the function as a filter: |
|||
<syntaxhighlight lang="jq">def stripchars(banish): |
|||
explode - (banish | explode) | implode;</syntaxhighlight> |
|||
In this case, we would write: |
|||
"She was a soul stripper. She took my heart!" | stripchars("aei") |
|||
=={{header|Julia}}== |
|||
{{works with|Julia|1.0}} |
|||
<syntaxhighlight lang="julia">stripChar = (s, r) -> replace(s, Regex("[$r]") => "")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>> stripChar("She was a soul stripper. She took my heart!", "aei") |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|K}}== |
|||
<syntaxhighlight lang="k">"She was a soul stripper. She took my heart!" ^ "aei"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>"Sh ws soul strppr. Sh took my hrt!"</pre> |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="kotlin">fun stripChars(s: String, r: String) = s.filter { it !in r } |
|||
fun main(args: Array<String>) { |
|||
println(stripChars("She was a soul stripper. She took my heart!", "aei")) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Lambdatalk}}== |
|||
Text substitutions are easy to process directly using regular expressions : |
|||
<syntaxhighlight lang="scheme"> |
|||
{S.replace (a|e|i) |
|||
by // nothing |
|||
in She was a soul stripper. She took my heart!} |
|||
-> Sh ws soul strppr. Sh took my hrt! |
|||
</syntaxhighlight> |
|||
and can be wrapped inside a fuction: |
|||
<syntaxhighlight lang="scheme"> |
|||
{def word2rex |
|||
{def word2rex.r |
|||
{lambda {:w} |
|||
{if {W.empty? {W.rest :w}} |
|||
then {W.first :w}) |
|||
else {W.first :w}|{word2rex.r {W.rest :w}}}}} |
|||
{lambda {:w :s} |
|||
{S.replace ({word2rex.r :w} by in :s}}} |
|||
-> word2rex |
|||
{word2rex aei |
|||
She was a soul stripper. She took my heart!} |
|||
-> Sh ws soul strppr. Sh took my hrt! |
|||
</syntaxhighlight> |
|||
=={{header|Lasso}}== |
|||
<syntaxhighlight lang="lasso">define stripper(in::string,destroy::string) => { |
|||
with toremove in #destroy->values do => { |
|||
#in->replace(#toremove,'') |
|||
} |
|||
return #in |
|||
} |
|||
stripper('She was a soul stripper. She took my heart!','aei')</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Liberty BASIC}}== |
|||
<syntaxhighlight lang="lb">Print stripchars$("She was a soul stripper. She took my heart!", "aei", 1) |
|||
End |
|||
Function stripchars$(strip$, chars$, num) |
|||
For i = 1 To Len(strip$) |
|||
If Mid$(strip$, i, 1) <> Mid$(chars$, num, 1) Then |
|||
stripchars$ = (stripchars$ + Mid$(strip$, i, 1)) |
|||
End If |
|||
Next i |
|||
If (num <= Len(chars$)) Then stripchars$ = stripchars$(stripchars$, chars$, (num + 1)) |
|||
End Function</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
|||
<syntaxhighlight lang="livecode">function stripChars str charlist |
|||
local strstripped |
|||
put str into strstripped |
|||
repeat for each char c in charlist |
|||
replace c with empty in strstripped |
|||
end repeat |
|||
return strstripped |
|||
end stripChars</syntaxhighlight> |
|||
Test<syntaxhighlight lang="livecode">command teststripchars |
|||
put stripchars("She was a soul stripper. She took my heart!","aei") |
|||
end teststripchars</syntaxhighlight>Output<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Logo}}== |
|||
<syntaxhighlight lang="logo">to strip :string :chars |
|||
output filter [not substringp ? :chars] :string |
|||
end |
|||
print strip "She\ was\ a\ soul\ stripper.\ She\ took\ my\ heart! "aei |
|||
bye</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Lua}}== |
|||
<syntaxhighlight lang="lua"> |
|||
function stripchars(str, chrs) |
|||
local s = str:gsub("["..chrs:gsub("%W","%%%1").."]", '') |
|||
return s |
|||
end |
|||
print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) ) |
|||
--> Sh ws soul strppr. Sh took my hrt! |
|||
print( stripchars( "She was a soul stripper. She took my heart!", "a-z" ) ) |
|||
--> She ws soul stripper. She took my hert! |
|||
</syntaxhighlight> |
|||
=={{header|Maple}}== |
|||
<syntaxhighlight lang="maple">with(StringTools): |
|||
Remove(c->Has("aei",c), "She was a soul stripper. She took my heart!");</syntaxhighlight> |
|||
Output: |
|||
<pre> "Sh ws soul strppr. Sh took my hrt!"</pre> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">stripchars[a_,b_]:=StringReplace[a,(#->"")&/@Characters[b]] |
|||
stripchars["She was a soul stripper. She took my heart!","aei"] |
|||
->Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
|||
<syntaxhighlight lang="matlab">function str = stripchars(str, charlist) |
|||
% MATLAB after 2016b: str = erase(str, charlist); |
|||
str(ismember(str, charlist)) = '';</syntaxhighlight> |
|||
{{out}} |
|||
<pre> >> stripchars('She was a soul stripper. She took my heart!','aei') |
|||
ans = Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Nanoquery}}== |
|||
<syntaxhighlight lang="nanoquery">def stripchars(string, chars) |
|||
for char in chars |
|||
string = string.replace(char, "") |
|||
end |
|||
return string |
|||
end</syntaxhighlight> |
|||
=={{header|Nemerle}}== |
|||
<syntaxhighlight lang="nemerle">StripChars( text : string, remove : string ) : string |
|||
{ |
|||
def chuck = Explode(remove); |
|||
Concat( "", Split(text, chuck)) |
|||
}</syntaxhighlight> |
|||
=={{header|NetRexx}}== |
|||
<syntaxhighlight lang="netrexx">/* NetRexx */ |
|||
options replace format comments java crossref savelog symbols |
|||
say stripchars("She was a soul stripper. She took my heart!", "aei") |
|||
return |
|||
method stripchars(haystack, chs) public static |
|||
loop c_ = 1 to chs.length |
|||
needle = chs.substr(c_, 1) |
|||
haystack = haystack.changestr(needle, '') |
|||
end c_ |
|||
return haystack</syntaxhighlight> |
|||
=={{header|NewLISP}}== |
|||
<syntaxhighlight lang="newlisp">(let (sentence "She was a soul stripper. She took my heart!") |
|||
(replace "[aei]" sentence "" 0))</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
<syntaxhighlight lang="nim">import strutils |
|||
echo "She was a soul stripper. She took my heart!".split({'a','e','i'}).join() |
|||
echo "She was a soul stripper. She took my heart!".multiReplace( |
|||
("a", ""), |
|||
("e", ""), |
|||
("i", "") |
|||
) |
|||
# And another way using module "sequtils". |
|||
import sequtils |
|||
echo "She was a soul stripper. She took my heart!".filterIt(it notin "aei").join() |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Objective-C}}== |
|||
{{works with|Mac OS X|10.5+}} |
|||
{{works with|iOS|1.0}} |
|||
<syntaxhighlight lang="objc">@interface NSString (StripCharacters) |
|||
- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars; |
|||
@end |
|||
@implementation NSString (StripCharacters) |
|||
- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars { |
|||
return [[self componentsSeparatedByCharactersInSet:chars] componentsJoinedByString:@""]; |
|||
} |
|||
@end</syntaxhighlight> |
|||
{{out|To use}} |
|||
<syntaxhighlight lang="objc"> NSString *aString = @"She was a soul stripper. She took my heart!"; |
|||
NSCharacterSet* chars = [NSCharacterSet characterSetWithCharactersInString:@"aei"]; |
|||
// Display the NSString. |
|||
NSLog(@"%@", [aString stripCharactersInSet:chars]);</syntaxhighlight> |
|||
=={{header|OCaml}}== |
|||
<syntaxhighlight lang="ocaml">let stripchars s cs = |
|||
let len = String.length s in |
let len = String.length s in |
||
let res = |
let res = Bytes.create len in |
||
let rec aux i j = |
let rec aux i j = |
||
if i >= len |
if i >= len |
||
then Bytes.to_string (Bytes.sub res 0 j) |
|||
else if String.contains cs s.[i] then |
else if String.contains cs s.[i] then |
||
aux (succ i) (j) |
aux (succ i) (j) |
||
else begin |
else begin |
||
Bytes.set res j s.[i]; |
|||
aux (succ i) (succ j) |
aux (succ i) (succ j) |
||
end |
end |
||
in |
in |
||
aux 0 0</ |
aux 0 0</syntaxhighlight> |
||
{{out|Testing in the toplevel}} |
|||
testing in the toplevel: |
|||
<pre># stripchars "She was a soul stripper. She took my heart!" "aei" ;; |
<pre># stripchars "She was a soul stripper. She took my heart!" "aei" ;; |
||
- : string = "Sh ws soul strppr. Sh took my hrt!"</pre> |
- : string = "Sh ws soul strppr. Sh took my hrt!"</pre> |
||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">String method: stripChars(str) #[ str include not ] self filter ; |
|||
"She was a soul stripper. She took my heart!" stripChars("aei") println</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|PARI/GP}}== |
|||
GP should not be used for string manipulation. A good solution to this problem would probably involve <code>system("perl -e</code>... |
|||
<syntaxhighlight lang="parigp">stripchars(s, bad)={ |
|||
bad=Set(Vec(Vecsmall(bad))); |
|||
s=Vecsmall(s); |
|||
my(v=[]); |
|||
for(i=1,#s,if(!setsearch(bad,s[i]),v=concat(v,s[i]))); |
|||
Strchr(v) |
|||
}; |
|||
stripchars("She was a soul stripper. She took my heart!","aei")</syntaxhighlight> |
|||
=={{header|Pascal}}== |
|||
See [[Strip_a_set_of_characters_from_a_string#Delphi|Delphi]] |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
function StripChars(s,chars: string): string |
|||
:= s.Where(c -> c not in chars).JoinToString; |
|||
begin |
|||
Print(StripChars('She was a soul stripper. She took my heart!','aei')); |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Note: this example uses a regular expression character class. Certain characters, like hyphens and brackets, may need to be escaped. |
|||
<lang perl>sub stripchars { |
|||
<syntaxhighlight lang="perl">sub stripchars { |
|||
my ($s, $chars) = @_; |
|||
$s =~ s/[$chars]//g; |
|||
return $s; |
|||
} |
|||
print stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
Another good option for stripping characters is to use the <code>tr///</code> operator. This option is very efficient when the set of characters to strip is fixed at compile time, because <code>tr///</code> is specifically designed for transforming and deleting characters. Note that hyphens also have special meaning in this case. |
|||
<syntaxhighlight lang="perl">$str =~ tr/aei//d;</syntaxhighlight> |
|||
Since the characters used for <code>tr///</code> must be fixed at compile time, unfortunately, it requires the use of an <code>eval</code> to do this generally for any set of characters provided at runtime: |
|||
<syntaxhighlight lang="perl">sub stripchars { |
|||
my ($s, $chars) = @_; |
my ($s, $chars) = @_; |
||
eval("\$s =~ tr/$chars//d;"); |
eval("\$s =~ tr/$chars//d;"); |
||
return $s; |
return $s; |
||
}</syntaxhighlight> |
|||
=={{header|Phix}}== |
|||
{{libheader|Phix/basics}} |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"She was a soul stripper. She took my heart!"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"out"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"aei"</span><span style="color: #0000FF;">)</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
"Sh ws soul strppr. Sh took my hrt!" |
|||
</pre> |
|||
=={{header|PHP}}== |
|||
<syntaxhighlight lang="php"><?php |
|||
function stripchars($s, $chars) { |
|||
return str_replace(str_split($chars), "", $s); |
|||
} |
} |
||
echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; |
|||
?></syntaxhighlight> |
|||
Output: |
|||
{{out}} |
|||
<pre> |
<pre> |
||
Sh ws soul strppr. Sh took my hrt! |
Sh ws soul strppr. Sh took my hrt! |
||
</pre> |
</pre> |
||
=={{header|Picat}}== |
|||
===List comprehension=== |
|||
<syntaxhighlight lang="picat">stripchars(String, Chars) = [C : C in String, not(membchk(C,Chars))].</syntaxhighlight> |
|||
===Recursion=== |
|||
<syntaxhighlight lang="picat">stripchars2(String,Chars, Res) => |
|||
stripchars2(String, Chars, [], Res). |
|||
stripchars2([], _Chars, Res, Res). |
|||
stripchars2([H|T], Chars, Res1, Res) :- |
|||
membchk(H,Chars), |
|||
stripchars2(T, Chars, Res1, Res). |
|||
stripchars2([H|T], Chars, Res1, [H|Res]) :- |
|||
stripchars2(T, Chars, Res1, Res).</syntaxhighlight> |
|||
===Test=== |
|||
<syntaxhighlight lang="picat">go => |
|||
S = "She was a soul stripper. She took my heart!", |
|||
println(stripchars(S, "aei")), |
|||
stripchars2(S, "aei", S2), |
|||
println(S2), |
|||
nl.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt! |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de strDiff (Str1 Str2) |
||
(pack (diff (chop Str1) (chop Str2))) )</ |
(pack (diff (chop Str1) (chop Str2))) )</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>: (strDiff "She was a soul stripper. She took my heart!" "aei") |
<pre>: (strDiff "She was a soul stripper. She took my heart!" "aei") |
||
-> "Sh ws soul strppr. Sh took my hrt!"</pre> |
-> "Sh ws soul strppr. Sh took my hrt!"</pre> |
||
=={{header|PL/I}}== |
|||
<syntaxhighlight lang="pl/i">strip_chars: procedure (text, chars) returns (character (100) varying); |
|||
declare text character (*) varying, chars character (*) varying; |
|||
declare out_text character (100); |
|||
declare ch character (1); |
|||
declare (i, j) fixed binary; |
|||
j = 0; |
|||
do i = 1 to length(text); |
|||
ch = substr(text, i, 1); |
|||
if index(chars, ch) = 0 then |
|||
do; j = j + 1; substr(out_text, j, 1) = ch; end; |
|||
end; |
|||
return (substr(out_text, 1, j) ); |
|||
end strip_chars;</syntaxhighlight> |
|||
=={{header|PL/M}}== |
|||
<syntaxhighlight lang="pli">100H: |
|||
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; |
|||
EXIT: PROCEDURE; GO TO 0; END EXIT; |
|||
PRINT: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT; |
|||
DECLARE TRUE LITERALLY '0FFH', FALSE LITERALLY '0'; |
|||
/* SEE IF STRING CONTAINS CHARACTER */ |
|||
CONTAINS: PROCEDURE(STR, CHR) BYTE; |
|||
DECLARE STR ADDRESS, (SCH BASED STR, CHR) BYTE; |
|||
DO WHILE SCH <> '$'; |
|||
IF SCH = CHR THEN RETURN TRUE; |
|||
STR = STR + 1; |
|||
END; |
|||
RETURN FALSE; |
|||
END CONTAINS; |
|||
/* STRIP CHARACTERS FROM A STRING */ |
|||
STRIP$CHARS: PROCEDURE(STR, CHARS, OUTBUF); |
|||
DECLARE (STR, CHARS, OUTBUF) ADDRESS; |
|||
DECLARE (IN$CH BASED STR, OUT$CH BASED OUTBUF) BYTE; |
|||
DO WHILE IN$CH <> '$'; |
|||
IF NOT CONTAINS(CHARS, IN$CH) THEN DO; |
|||
OUT$CH = IN$CH; |
|||
OUTBUF = OUTBUF + 1; |
|||
END; |
|||
STR = STR + 1; |
|||
END; |
|||
OUT$CH = '$'; |
|||
END STRIP$CHARS; |
|||
/* TEST */ |
|||
DECLARE BUF (128) ADDRESS; |
|||
/* 8080 PL/M DOES NOT SUPPORT LOWERCASE OR EXCLAMATION MARK */ |
|||
CALL STRIP$CHARS( |
|||
.'SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART.$', |
|||
.'AEI$', |
|||
.BUF); |
|||
CALL PRINT(.BUF); |
|||
CALL EXIT; |
|||
EOF</syntaxhighlight> |
|||
{{out}} |
|||
<pre>SH WS SOUL STRPPR. SH TOOK MY HRT.</pre> |
|||
=={{header|Powershell}}== |
|||
Powershell have replace operator that by will replace a regex pattern with a given string: |
|||
<syntaxhighlight lang="powershell">'She was a soul stripper. She took my heart!' -replace '[aei]', '' |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</syntaxhighlight> |
|||
=={{header|Prolog}}== |
|||
Works with SWI-Prolog and module '''lambda.pl''' written by '''Ulrich Neumerkel''' found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl . |
|||
<syntaxhighlight lang="prolog">:- use_module(library(lambda)). |
|||
stripchars(String, Exclude, Result) :- |
|||
exclude(\X^(member(X, Exclude)), String, Result1), |
|||
string_to_list(Result, Result1). |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> ?- stripchars("She was a soul stripper. She took my heart!","aei", R). |
|||
R = "Sh ws soul strppr. Sh took my hrt!". |
|||
</pre> |
|||
=== alternative version using DCG strings === |
|||
<syntaxhighlight lang="prolog"> |
|||
:- system:set_prolog_flag(double_quotes,chars) . |
|||
%! strip_chars(SOURCEz0,SETz0,TARGETz) |
|||
% |
|||
% `TARGETz` is `SOURCEz0` but with any of the characters in `SETz0` removed . |
|||
strip_chars(SOURCEz0,SETz0,TARGETz) |
|||
:- |
|||
prolog:phrase(strip_chars(SOURCEz0,SETz0),TARGETz) |
|||
. |
|||
strip_chars([],_SETz0_) --> ! . |
|||
strip_chars([SOURCE0|SOURCEz0],SETz0) |
|||
--> |
|||
{ \+ \+ lists:member(SOURCE0,SETz0) } , |
|||
! , |
|||
strip_chars(SOURCEz0,SETz0) |
|||
. |
|||
strip_chars([SOURCE0|SOURCEz0],SETz0) |
|||
--> |
|||
[SOURCE0] , |
|||
strip_chars(SOURCEz0,SETz0) |
|||
. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
?- strip_chars("She was a soul stripper. She took my heart!","aei",Rs) . |
|||
Rs = ['S', h, ' ', w, s, ' ', ' ', s, o, u, l, ' ', s, t, r, p, p, r, '.', ' ', 'S', h, ' ', t, o, o, k, ' ', m, y, ' ', h, r, t, !]. |
|||
</pre> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
PureBasic uses a single (for ASCII) or a two-byte (for Unicode) null to signal the end of a string. Nulls are thus excluded from the allowable characters to strip as they can't be included in a PureBasic string. |
PureBasic uses a single (for ASCII) or a two-byte (for Unicode) null to signal the end of a string. Nulls are thus excluded from the allowable characters to strip as they can't be included in a PureBasic string. |
||
< |
<syntaxhighlight lang="purebasic">Procedure.s stripChars(source.s, charsToStrip.s) |
||
Protected i, *ptrChar.Character, length = Len(source), result.s |
Protected i, *ptrChar.Character, length = Len(source), result.s |
||
*ptrChar = @source |
*ptrChar = @source |
||
Line 105: | Line 2,345: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
|||
Sample output: |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Not using regular expressions=== |
|||
{{works with|Python|2.6+}} |
{{works with|Python|2.6+}} |
||
< |
<syntaxhighlight lang="python">>>> def stripchars(s, chars): |
||
... return s.translate(None, chars) |
... return s.translate(None, chars) |
||
... |
... |
||
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
||
'Sh ws soul strppr. Sh took my hrt!'</ |
'Sh ws soul strppr. Sh took my hrt!'</syntaxhighlight> |
||
{{works with|Python|2.x}} |
{{works with|Python|2.x}} |
||
< |
<syntaxhighlight lang="python">>>> import string |
||
>>> def stripchars(s, chars): |
>>> def stripchars(s, chars): |
||
... return s.translate(string.maketrans("", ""), chars) |
... return s.translate(string.maketrans("", ""), chars) |
||
... |
... |
||
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
||
'Sh ws soul strppr. Sh took my hrt!'</ |
'Sh ws soul strppr. Sh took my hrt!'</syntaxhighlight> |
||
Implemented manually: |
Implemented manually: |
||
< |
<syntaxhighlight lang="python">>>> def stripchars(s, chars): |
||
... return "".join(c for c in s if c not in chars) |
... return "".join(c for c in s if c not in chars) |
||
... |
... |
||
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
||
'Sh ws soul strppr. Sh took my hrt!'</ |
'Sh ws soul strppr. Sh took my hrt!'</syntaxhighlight> |
||
===Using regular expressions=== |
|||
<syntaxhighlight lang="python">>>> import re |
|||
>>> def stripchars(s, chars): |
|||
return re.sub('[%s]+' % re.escape(chars), '', s) |
|||
>>> stripchars("She was a soul stripper. She took my heart!", "aei") |
|||
'Sh ws soul strppr. Sh took my hrt!' |
|||
>>> </syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery"> [ $ "" swap witheach [ upper join ] ] is upper$ ( $ --> $ ) |
|||
[ $ "" swap witheach [ lower join ] ] is lower$ ( $ --> $ ) |
|||
[ 0 swap witheach [ bit | ] ] is ->set ( [ --> s ) |
|||
[ bit & not ] is !in ( s c --> b ) |
|||
[ $ "" unrot |
|||
upper$ dup lower$ join ( omit this line for case-sensitive ) |
|||
->set swap witheach |
|||
[ 2dup !in iff |
|||
[ swap dip join ] |
|||
else drop ] drop ] is strip$ ( $ $ --> $ ) |
|||
$ "One is never alone with a rubber duck." dup echo$ cr |
|||
$ "EIU" strip$ echo$ cr</syntaxhighlight> |
|||
{{out}} |
|||
<pre>One is never alone with a rubber duck. |
|||
On s nvr alon wth a rbbr dck.</pre> |
|||
=={{header|Racket}}== |
|||
<syntaxhighlight lang="racket"> |
|||
#lang racket |
|||
;; Using list operations |
|||
(define (stripchars1 text chars) |
|||
(list->string (remove* (string->list chars) (string->list text)))) |
|||
;; Using a regexp |
|||
;; => will be broken if chars have "-" or "]" or "\\" |
|||
(define (stripchars2 text chars) |
|||
(regexp-replace* (~a "[" chars "]+") text "")) |
|||
</syntaxhighlight> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
<syntaxhighlight lang="raku" line>sub strip_chars ( $s, $chars ) { |
|||
return $s.trans( $chars.comb X=> '' ); |
|||
} |
|||
say strip_chars( 'She was a soul stripper. She took my heart!', 'aei' );</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Red}}== |
|||
<syntaxhighlight lang="red"> |
|||
stripchars: func [str chars] [trim/with str chars] |
|||
stripchars "She was a soul stripper. She took my heart!" "aei"</syntaxhighlight> |
|||
=={{header|Refal}}== |
|||
<syntaxhighlight lang="refal">$ENTRY Go { |
|||
= <Prout <Strip ('aei') 'She was a soul stripper. She took my heart!'>>; |
|||
}; |
|||
Strip { |
|||
(e.Chs) = ; |
|||
(e.Chs) s.C e.S, e.Chs: e.1 s.C e.2 = <Strip (e.Chs) e.S>; |
|||
(e.Chs) s.C e.S = s.C <Strip (e.Chs) e.S>; |
|||
};</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|REXX}}== |
|||
===version 1=== |
|||
In the REXX language, '''strip''' usually means to remove leading and/or trailing characters from a string (most often, blanks). |
|||
<syntaxhighlight lang="rexx">/*REXX program removes a list of characters from a string (the haystack). */ |
|||
say stripChars('She was a soul stripper. She took my heart!', "iea") /*elide: iea */ |
|||
exit /*stick a fork in it, we're all done. */ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
stripChars: procedure; parse arg haystack, remove |
|||
do j=1 for length(remove) |
|||
haystack=changestr( substr( remove, j, 1), haystack, '') |
|||
end /*j*/ |
|||
return haystack</syntaxhighlight> |
|||
Some older REXXes don't have a '''changestr''' BIF, so one is included here ───► [[CHANGESTR.REX]]. |
|||
<br><br> |
|||
{{out|output|text=:}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
===version 2=== |
|||
Using recursion: |
|||
<syntaxhighlight lang="rexx">/* REXX */ |
|||
say StripChars('She was a soul stripper. She took my heart!','iea') |
|||
exit 0 |
|||
StripChars: procedure |
|||
parse arg strng,remove |
|||
removepos=Verify(strng,remove,'MATCH') |
|||
if removepos=0 then return strng |
|||
parse value strng with strng =(removepos) +1 rest |
|||
return strng || StripChars(rest,remove)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hart!rt!</pre> |
|||
===version 3=== |
|||
This works on all Rexxes. |
|||
<br>(Except for R4 and ROO at the least, there may be others.) |
|||
<syntaxhighlight lang="rexx"> |
|||
/* REXX *************************************************************** |
|||
* If source and stripchars don't contain a hex 00 character, this works |
|||
* 06.07.2012 Walter Pachl |
|||
* 19.06.2013 -"- space(result,0) -> space(result,0,' ') |
|||
* space(result,0) removes WHITESPACE not only blanks |
|||
**********************************************************************/ |
|||
Say 'Sh ws soul strppr. Sh took my hrt! -- expected' |
|||
Say stripchars("She was a soul stripper. She took my heart!","aei") |
|||
Exit |
|||
stripchars: Parse Arg string,stripchars |
|||
result=translate(string,'00'x,' ') /* turn blanks into '00'x */ |
|||
result=translate(result,' ',stripchars) /* turn stripchars into ' ' */ |
|||
result=space(result,0,' ') /* remove all blanks */ |
|||
Return translate(result,' ','00'x) /* '00'x back to blanks */ |
|||
</syntaxhighlight> |
|||
===version 4=== |
|||
Another neat (?) one |
|||
No x00 restriction and no changestr |
|||
<syntaxhighlight lang="rexx"> |
|||
stripchars: Procedure |
|||
Parse Arg i,s /* get input and chars to be removed */ |
|||
o='' /* initialize result */ |
|||
Do While i\=='' /* loop through input */ |
|||
Parse Var i c +1 i /* get one character */ |
|||
If pos(c,s)=0 Then /* it's not to be removed */ |
|||
o=o||c /* append it to the result */ |
|||
End |
|||
Return o /* return the result */ |
|||
</syntaxhighlight> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
aList = "She was a soul stripper. She took my heart!" |
|||
bList = "aei" |
|||
see aList + nl |
|||
see stripChars(aList,bList) |
|||
func stripChars cList, dList |
|||
for n = 1 to len(dList) |
|||
cList = substr(cList,dList[n],"") + nl |
|||
next |
|||
return cList |
|||
</syntaxhighlight> |
|||
=={{header|RPL}}== |
|||
≪ → string out |
|||
≪ "" 1 string SIZE '''FOR''' j |
|||
string j DUP SUB |
|||
'''IF''' out OVER POS '''THEN''' DROP '''ELSE''' + '''END''' |
|||
'''NEXT''' |
|||
≫ ≫ 'STRIP' STO |
|||
{{in}} |
|||
<pre> |
|||
"She was a soul stripper. She took my heart!" "aei" STRIP |
|||
</pre> |
|||
{{in}} |
|||
<pre> |
|||
1: "Sh ws soul strppr. Sh took my hrt!" |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">"She was a soul stripper. She took my heart!".delete("aei") # => "Sh ws soul strppr. Sh took my hrt!"</syntaxhighlight> |
||
=> "Sh ws soul strppr. Sh took my hrt!"</lang> |
|||
=={{header|Run BASIC}}== |
|||
<syntaxhighlight lang="runbasic">function stripchars(texto, remove) |
|||
s = texto |
|||
for i = 1 to length(remove) |
|||
s = replace(s, mid(remove, i, 1), "", true) |
|||
next i |
|||
return s |
|||
end function</syntaxhighlight> |
|||
=={{header|Rust}}== |
|||
Naive Implementation: |
|||
<syntaxhighlight lang="rust"> |
|||
fn strip_characters(original : &str, to_strip : &str) -> String { |
|||
let mut result = String::new(); |
|||
for c in original.chars() { |
|||
if !to_strip.contains(c) { |
|||
result.push(c); |
|||
} |
|||
} |
|||
result |
|||
} |
|||
</syntaxhighlight> |
|||
Functional Implementation: |
|||
<syntaxhighlight lang="rust"> |
|||
fn strip_characters(original : &str, to_strip : &str) -> String { |
|||
original.chars().filter(|&c| !to_strip.contains(c)).collect() |
|||
} |
|||
</syntaxhighlight> |
|||
Either can be executed thusly: |
|||
<syntaxhighlight lang="rust"> |
|||
fn main() { |
|||
println!("{}", strip_characters("She was a soul stripper. She took my heart!", "aei")); |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|SAS}}== |
|||
This code will write the resulting string to the log: |
|||
<syntaxhighlight lang="sas">%let string=She was a soul stripper. She took my heart!; |
|||
%let chars=aei; |
|||
%let stripped=%sysfunc(compress("&string","&chars")); |
|||
%put &stripped;</syntaxhighlight> |
|||
Log: |
|||
<syntaxhighlight lang="sas">Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
=={{header|S-BASIC}}== |
|||
<syntaxhighlight lang="BASIC"> |
|||
rem - strip unwanted characters from a string |
|||
function strip(s, unwanted = string) = string |
|||
var i = integer |
|||
var outstr = string |
|||
var ch = char |
|||
outstr = "" |
|||
for i = 1 to len(s) |
|||
ch = mid(s, i, 1) |
|||
if instr(1, unwanted, ch) = 0 then |
|||
outstr = outstr + ch |
|||
next i |
|||
end = outstr |
|||
rem - exercise the routine |
|||
print strip("She was a soul stripper. She took my heart!","aei") |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Scala}}== |
|||
<syntaxhighlight lang="scala">def stripChars(s:String, ch:String)= s filterNot (ch contains _) |
|||
stripChars("She was a soul stripper. She took my heart!", "aei") |
|||
// => Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
|||
=={{header|Scheme}}== |
|||
Two approaches are given here. The first is in plain Scheme, and implements a loop to remove the characters. |
|||
The second uses the SRFI libraries to create a character set and delete those characters from the string. |
|||
<syntaxhighlight lang="scheme"> |
|||
(import (scheme base) |
|||
(scheme write) |
|||
(only (srfi 13) string-delete) |
|||
(only (srfi 14) ->char-set)) |
|||
;; implementation in plain Scheme |
|||
(define (strip-chars str chars) |
|||
(let ((char-list (string->list chars))) |
|||
(define (do-strip str-list result) |
|||
(cond ((null? str-list) |
|||
(reverse result)) |
|||
((member (car str-list) char-list char=?) |
|||
(do-strip (cdr str-list) result)) |
|||
(else |
|||
(do-strip (cdr str-list) (cons (car str-list) result))))) |
|||
(list->string |
|||
(do-strip (string->list str) '())))) |
|||
(display (strip-chars "She was a soul stripper. She took my heart!" "aei")) |
|||
(newline) |
|||
;; using functions in SRFI 13 and SRFI 14 |
|||
(define (strip-chars2 str chars) |
|||
(string-delete (->char-set chars) str)) |
|||
(display (strip-chars2 "She was a soul stripper. She took my heart!" "aei")) |
|||
(newline) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|ScriptBasic}}== |
|||
<syntaxhighlight lang="scriptbasic"> |
|||
str1 = "She was a soul stripper. She took my heart!" |
|||
rmv = "aei" |
|||
FOR i = 1 TO LEN(rmv) |
|||
str1 = REPLACE(str1, MID(rmv, i, 1), "") |
|||
NEXT |
|||
PRINT str1,"\n" |
|||
</syntaxhighlight> |
|||
=={{header|Sed}}== |
|||
Using echo and piping it through a sed filter: |
|||
<syntaxhighlight lang="bash">#!/bin/bash |
|||
strip_char() |
|||
{ |
|||
echo "$1" | sed "s/[$2]//g" |
|||
}</syntaxhighlight> |
|||
=={{header|Seed7}}== |
|||
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
|||
const func string: stripchars (in string: mainStri, in string: charList) is func |
|||
result |
|||
var string: strippedStri is ""; |
|||
local |
|||
var char: ch is ' '; |
|||
begin |
|||
strippedStri := mainStri; |
|||
for ch range charList do |
|||
strippedStri := replace(strippedStri, str(ch), ""); |
|||
end for; |
|||
end func; |
|||
const proc: main is func |
|||
begin |
|||
writeln(stripchars("She was a soul stripper. She took my heart!", "aei")); |
|||
end func;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|SETL}}== |
|||
<syntaxhighlight lang="setl">program strip_chars; |
|||
print(strip("She was a soul stripper. She took my heart!", "aei")); |
|||
proc strip(s, chs); |
|||
return +/[c : c in s | not c in chs]; |
|||
end proc; |
|||
end program;</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Sidef}}== |
|||
<syntaxhighlight lang="ruby">func stripchars(str, char_list) { |
|||
str.tr(char_list, "", "d"); |
|||
}</syntaxhighlight> |
|||
or: |
|||
<syntaxhighlight lang="ruby">func stripchars(str, char_list) { |
|||
str.chars.grep {|c| !char_list.contains(c)}.join; |
|||
}</syntaxhighlight> |
|||
Calling the function: |
|||
<syntaxhighlight lang="ruby">say stripchars("She was a soul stripper. She took my heart!", "aei");</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Slope}}== |
|||
This example ignores all type/error checking in favor of brevity and assumes |
|||
two strings will be given. A solution could also likely be crafted using '''regex-replace''' |
|||
or '''string-replace'''. |
|||
<syntaxhighlight lang="slope">(define strip-chars (lambda (str chrs) |
|||
(define chr-list (map (lambda (ch) (string->rune ch)) (string->list chrs))) |
|||
(list->string |
|||
(filter |
|||
(lambda (ch) (not (member? chr-list (string->rune ch)))) |
|||
(string->list str))))) |
|||
(display (strip-chars "She was a soul stripper. She took my heart!" "aei"))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Smalltalk}}== |
|||
{{works with|Pharo|1.3-13315}} |
|||
<syntaxhighlight lang="smalltalk">| stripChars | |
|||
stripChars := [ :string :chars | |
|||
string reject: [ :c | chars includes: c ] ]. |
|||
stripChars |
|||
value: 'She was a soul stripper. She took my heart!' |
|||
value: 'aei'. |
|||
"'Sh ws soul strppr. Sh took my hrt!'"</syntaxhighlight> |
|||
=={{header|SNOBOL4}}== |
|||
Note: "strip" is a function, its argument, the label of its first executed line, and its returned value. |
|||
<syntaxhighlight lang="snobol4"> DEFINE("strip(strip,c)") :(strip_end) |
|||
strip strip ANY(c) = :S(strip)F(RETURN) |
|||
strip_end |
|||
chars = HOST(2, HOST(3)) ;* Get command line argument |
|||
chars = IDENT(chars) "aei" |
|||
again line = INPUT :F(END) |
|||
OUTPUT = strip(line, chars) :(again) |
|||
END</syntaxhighlight> |
|||
{{out}} |
|||
<pre>snobol4 strip.sno aei |
|||
She was a soul stripper. She took my heart. |
|||
Sh ws soul strppr. Sh took my hrt.</pre> |
|||
=={{header|Standard ML}}== |
|||
<syntaxhighlight lang="sml">fun stripchars (string, chars) = let |
|||
fun aux c = |
|||
if String.isSubstring (str c) chars then |
|||
"" |
|||
else |
|||
str c |
|||
in |
|||
String.translate aux string |
|||
end</syntaxhighlight> |
|||
{{out|Testing}} |
|||
<pre>- stripchars ("She was a soul stripper. She took my heart!", "aei") ; |
|||
val it = "Sh ws soul strppr. Sh took my hrt!" : string</pre> |
|||
Alternately: |
|||
<syntaxhighlight lang="sml">fun stripchars (string, chars) = |
|||
String.concat (String.tokens (fn c => String.isSubstring (str c) chars) string)</syntaxhighlight> |
|||
{{out|Testing}} |
|||
<pre>- stripchars ("She was a soul stripper. She took my heart!", "aei") ; |
|||
val it = "Sh ws soul strppr. Sh took my hrt!" : string</pre> |
|||
=={{header|Stringle}}== |
|||
<syntaxhighlight lang="stringle">a "She was a soul stripper. She took my heart!" |
|||
b "aei" |
|||
#a |
|||
c c .a |
|||
b %.\c #c #:c |
|||
a :a |
|||
#a |
|||
$ c |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Swift}}== |
|||
<syntaxhighlight lang="swift">extension String { |
|||
func stripCharactersInSet(chars: [Character]) -> String { |
|||
return String(seq: filter(self) {find(chars, $0) == nil}) |
|||
} |
|||
} |
|||
let aString = "She was a soul stripper. She took my heart!" |
|||
let chars: [Character] = ["a", "e", "i"] |
|||
println(aString.stripCharactersInSet(chars))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc stripchars {str chars} { |
||
foreach c [split $chars ""] {set str [string map [list $c ""] $str]} |
foreach c [split $chars ""] {set str [string map [list $c ""] $str]} |
||
return $str |
return $str |
||
Line 143: | Line 2,839: | ||
set s "She was a soul stripper. She took my heart!" |
set s "She was a soul stripper. She took my heart!" |
||
puts [stripchars $s "aei"]</ |
puts [stripchars $s "aei"]</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
|||
This uses a default function. |
|||
$string = "She was a soul stripper. She took my heart!"; |
|||
$chars = "aei"; |
|||
$newString = stripChars($string, $chars); |
|||
echo($string); |
|||
echo($newString); |
|||
Output: |
|||
She was a soul stripper. She took my heart! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
=={{header|Transd}}== |
|||
<syntaxhighlight lang="scheme">#lang transd |
|||
MainModule: { |
|||
_start: (λ |
|||
(with s "She was a soul stripper. She took my heart!" |
|||
(textout (replace s "(a|e|i)" ""))) |
|||
) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|True BASIC}}== |
|||
<syntaxhighlight lang="qbasic">FUNCTION stripchars$(text$, remove$) |
|||
LET s$ = text$ |
|||
FOR i = 1 TO LEN(remove$) |
|||
DO |
|||
LET t = POS(s$, (remove$)[i:i]) |
|||
IF t <> 0 THEN LET s$ = (s$)[1:t-1] & (s$)[t+1:maxnum] ELSE EXIT DO |
|||
LOOP |
|||
NEXT i |
|||
LET stripchars$ = s$ |
|||
END FUNCTION |
|||
PRINT stripchars$("She was a soul stripper. She took my heart!", "aei") |
|||
END</syntaxhighlight> |
|||
=={{header|TUSCRIPT}}== |
|||
<syntaxhighlight lang="tuscript"> |
|||
$$ MODE TUSCRIPT,{} |
|||
string="She was a soul stripper. She took my heart!" |
|||
stringstrip=EXCHANGE (string,"_[aei]__") |
|||
print string |
|||
print stringstrip |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
She was a soul stripper. She took my heart! |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|TXR}}== |
|||
This solution builds up a regular expression in a hygienic way from the set of characters given as a string. |
|||
The string is broken into a list, which is used to construct a regex abstract syntax tree for a character set match, using a Lisp quasiquote. This is fed to the regex compiler, which produces an executable machine that is then used with <code>regsub</code>. |
|||
On the practical side, some basic structural pattern matching is used to process command line argument list. |
|||
Since the partial argument list (the arguments belonging to the TXR script) is a suffix of the full argument list (the complete arguments which include the invoking command and the script name), the classic Lisp function <code>ldiff</code> comes in handy in obtaining just the prefix, for printing the usage: |
|||
<syntaxhighlight lang="txrlisp">(defun strip-chars (str set) |
|||
(let* ((regex-ast ^(set ,*(list-str set))) |
|||
(regex-obj (regex-compile regex-ast))) |
|||
(regsub regex-obj "" str))) |
|||
(defun usage () |
|||
(pprinl `usage: @{(ldiff *full-args* *args*) " "} <string> <set>`) |
|||
(exit 1)) |
|||
(tree-case *args* |
|||
((str set extra) (usage)) |
|||
((str set . junk) (pprinl (strip-chars str set))) |
|||
(else (usage)))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ txr strip-chars-2.tl |
|||
usage: txr strip-chars-2.tl <string> <set> |
|||
$ txr strip-chars-2.tl "she was a soul stripper. she stole my heart." "aei" |
|||
sh ws soul strppr. sh stol my hrt.</pre> |
|||
Now here is a rewrite of <code>strip-chars</code> which just uses classic Lisp that has been generalized to work over strings, plus the <code>do</code> syntax (a sibling of the <code>op</code> operator) that provides syntactic sugar for a lambda function whose body is an operator or macro form. |
|||
<syntaxhighlight lang="txr">(defun strip-chars (str set) |
|||
(mappend (do if (memq @1 set) (list @1)) str))</syntaxhighlight> |
|||
<code>(do if (memq @1 set) (list @1))</code> is just <code>(lambda (item) (if (memq item set) (list item)))</code>. |
|||
<code>mappend</code> happily maps over strings and since the leftmost input sequence is a string, and the return values of the lambda are sequence of characters, <code>mappend</code> produces a string. |
|||
=={{header|UNIX Shell}}== |
|||
One would normally do this using the standard tr(1) command: |
|||
{{works with|sh}} |
|||
<syntaxhighlight lang="bash">strip_chars() { |
|||
echo "$1" | tr -d "$2" |
|||
}</syntaxhighlight> |
|||
But it can also be accomplished with bash's built-in parameter expansions: |
|||
{{works with|bash}} |
|||
<syntaxhighlight lang="bash">function strip_chars { |
|||
echo "${1//[$2]}" |
|||
}</syntaxhighlight> |
|||
Test code: |
|||
<syntaxhighlight lang="bash"> strip_chars "She was a soul stripper. She took my heart!" aei</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|Ursala}}== |
|||
Normally there's no need to define this operation because it's built in. |
|||
<syntaxhighlight lang="ursala">strip = ~&j |
|||
#cast %s |
|||
test = strip('she was a soul stripper. she took my heart','aei')</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
'sh ws soul strppr. sh took my hrt' |
|||
</pre> |
|||
{{omit from|Bc}} |
|||
{{omit from|Openscad}} |
|||
=={{header|VBA}}== |
|||
Pass the optional bSpace parameter True to replace stripped characters with spaces, otherwise replaced with null. |
|||
<syntaxhighlight lang="vb">Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) |
|||
Dim i As Integer, stReplace As String |
|||
If bSpace = True Then |
|||
stReplace = " " |
|||
Else |
|||
stReplace = "" |
|||
End If |
|||
For i = 1 To Len(stStripChars) |
|||
stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) |
|||
Next i |
|||
StripChars = stString |
|||
End Function</syntaxhighlight> |
|||
{{out}} |
|||
<pre>' with bSpace = True: |
|||
Sh w s soul str pp r. Sh took my h rt! |
|||
'with bSpace = False / omitted: |
|||
Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|VBScript}}== |
|||
<syntaxhighlight lang="vb"> |
|||
Function stripchars(s1,s2) |
|||
For i = 1 To Len(s1) |
|||
If InStr(s2,Mid(s1,i,1)) Then |
|||
s1 = Replace(s1,Mid(s1,i,1),"") |
|||
End If |
|||
Next |
|||
stripchars = s1 |
|||
End Function |
|||
WScript.StdOut.Write stripchars("She was a soul stripper. She took my heart!","aei") |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>Sh ws soul strppr. Sh took my hrt!</pre> |
|||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">fn main() { |
|||
println(stripchars("She was a soul stripper. She took my heart!","aei")) |
|||
} |
|||
fn stripchars(str string, charstrip string) string { |
|||
mut newstr := str |
|||
for element in charstrip {newstr = newstr.replace(element.ascii_str(), '')} |
|||
return newstr |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">var stripChars = Fn.new { |s, t| |
|||
return s.map { |c| |
|||
return (t.indexOf(c) == -1) ? c : "" |
|||
}.join() |
|||
} |
|||
System.print(stripChars.call("She was a soul stripper. She took my heart!", "aei"))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|XPL0}}== |
|||
<syntaxhighlight lang="xpl0">string 0; \make strings zero-terminated |
|||
func In(Char, Chars); \Is Char in the string Chars? |
|||
char Char, Chars; |
|||
int I; |
|||
for I:= 0 to -1>>1 do \for many times... |
|||
[if Chars(I) = 0 then return false; |
|||
if Chars(I) = Char then return true; |
|||
]; |
|||
func StripChars(String, Chars); \Remove Chars from String |
|||
char String, Chars; |
|||
int I, O; |
|||
[O:= 0; |
|||
for I:= 0 to -1>>1 do \for many times... |
|||
[if not In(String(I), Chars) then |
|||
[String(O):= String(I); O:= O+1]; |
|||
if String(I)=0 then return String; |
|||
]; |
|||
]; |
|||
Text(0, StripChars("She was a soul stripper. She took my heart!", "aei"))</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Sh ws soul strppr. Sh took my hrt! |
|||
</pre> |
|||
=={{header|Yabasic}}== |
|||
<syntaxhighlight lang="yabasic">sub stripchars$(text$, remove$) |
|||
local i, t, s$ |
|||
s$ = text$ |
|||
for i = 1 to len(remove$) |
|||
do |
|||
t = instr(s$, mid$(remove$, i, 1)) |
|||
if t then s$ = left$(s$, t - 1) + mid$(s$, t + 1) else break : fi |
|||
loop |
|||
next i |
|||
return s$ |
|||
end sub |
|||
print stripchars$("She was a soul stripper. She took my heart!", "aei")</syntaxhighlight> |
|||
=={{header|zkl}}== |
|||
<syntaxhighlight lang="zkl">println("She was a soul stripper. She took my heart!" - "aei") |
|||
//-->Sh ws soul strppr. Sh took my hrt!</syntaxhighlight> |
Revision as of 10:09, 9 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
- a string to be stripped
- a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print stripchars("She was a soul stripper. She took my heart!","aei")
Sh ws soul strppr. Sh took my hrt!
- Metrics
- Counting
- Word frequency
- Letter frequency
- Jewels and stones
- I before E except after C
- Bioinformatics/base count
- Count occurrences of a substring
- Count how many vowels and consonants occur in a string
- Remove/replace
- XXXX redacted
- Conjugate a Latin verb
- Remove vowels from a string
- String interpolation (included)
- Strip block comments
- Strip comments from a string
- Strip a set of characters from a string
- Strip whitespace from a string -- top and tail
- Strip control codes and extended characters from a string
- Anagrams/Derangements/shuffling
- Word wheel
- ABC problem
- Sattolo cycle
- Knuth shuffle
- Ordered words
- Superpermutation minimisation
- Textonyms (using a phone text pad)
- Anagrams
- Anagrams/Deranged anagrams
- Permutations/Derangements
- Find/Search/Determine
- ABC words
- Odd words
- Word ladder
- Semordnilap
- Word search
- Wordiff (game)
- String matching
- Tea cup rim text
- Alternade words
- Changeable words
- State name puzzle
- String comparison
- Unique characters
- Unique characters in each string
- Extract file extension
- Levenshtein distance
- Palindrome detection
- Common list elements
- Longest common suffix
- Longest common prefix
- Compare a list of strings
- Longest common substring
- Find common directory path
- Words from neighbour ones
- Change e letters to i in words
- Non-continuous subsequences
- Longest common subsequence
- Longest palindromic substrings
- Longest increasing subsequence
- Words containing "the" substring
- Sum of the digits of n is substring of n
- Determine if a string is numeric
- Determine if a string is collapsible
- Determine if a string is squeezable
- Determine if a string has all unique characters
- Determine if a string has all the same characters
- Longest substrings without repeating characters
- Find words which contains all the vowels
- Find words which contains most consonants
- Find words which contains more than 3 vowels
- Find words which first and last three letters are equals
- Find words which odd letters are consonants and even letters are vowels or vice_versa
- Formatting
- Substring
- Rep-string
- Word wrap
- String case
- Align columns
- Literals/String
- Repeat a string
- Brace expansion
- Brace expansion using ranges
- Reverse a string
- Phrase reversals
- Comma quibbling
- Special characters
- String concatenation
- Substring/Top and tail
- Commatizing numbers
- Reverse words in a string
- Suffixation of decimal numbers
- Long literals, with continuations
- Numerical and alphabetical suffixes
- Abbreviations, easy
- Abbreviations, simple
- Abbreviations, automatic
- Song lyrics/poems/Mad Libs/phrases
- Mad Libs
- Magic 8-ball
- 99 Bottles of Beer
- The Name Game (a song)
- The Old lady swallowed a fly
- The Twelve Days of Christmas
- Tokenize
- Text between
- Tokenize a string
- Word break problem
- Tokenize a string with escaping
- Split a character string based on change of character
- Sequences
11l
F stripchars(s, chars)
R s.filter(c -> c !C @chars).join(‘’)
print(stripchars(‘She was a soul stripper. She took my heart!’, ‘aei’))
- Output:
Sh ws soul strppr. Sh took my hrt!
360 Assembly
The program uses two ASSIST macro (XDECO,XPRNT) to keep the code as short as possible.
* Strip a set of characters from a string 07/07/2016
STRIPCH CSECT
USING STRIPCH,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
LA R1,PARMLIST parameter list
BAL R14,STRIPCHR c3=stripchr(c1,c2)
LA R2,PG @pg
LH R3,C3 length(c3)
LA R4,C3+2 @c3
LR R5,R3 length(c3)
MVCL R2,R4 pg=c3
XPRNT PG,80 print buffer
L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
PARMLIST DC A(C3) @c3
DC A(C1) @c1
DC A(C2) @c2
C1 DC H'43',CL62'She was a soul stripper. She took my heart!'
C2 DC H'3',CL14'aei' c2 [varchar(14)]
C3 DS H,CL62 c3 [varchar(62)]
PG DC CL80' ' buffer [char(80)]
*------- stripchr -----------------------------------------------------
STRIPCHR L R9,0(R1) @parm1
L R2,4(R1) @parm2
L R3,8(R1) @parm3
MVC PHRASE(64),0(R2) phrase=parm2
MVC REMOVE(16),0(R3) remove=parm3
SR R8,R8 k=0
LA R6,1 i=1
LOOPI CH R6,PHRASE do i=1 to length(phrase)
BH ELOOPI "
LA R4,PHRASE+1 @phrase
AR R4,R6 +i
MVC CI(1),0(R4) ci=substr(phrase,i,1)
MVI OK,X'01' ok='1'B
LA R7,1 j=1
LOOPJ CH R7,REMOVE do j=1 to length(remove)
BH ELOOPJ "
LA R4,REMOVE+1 @remove
AR R4,R7 +j
MVC CJ,0(R4) cj=substr(remove,j,1)
CLC CI,CJ if ci=cj
BNE CINECJ then
MVI OK,X'00' ok='0'B
B ELOOPJ leave j
CINECJ LA R7,1(R7) j=j+1
B LOOPJ end do j
ELOOPJ CLI OK,X'01' if ok
BNE NOTOK then
LA R8,1(R8) k=k+1
LA R4,RESULT+1 @result
AR R4,R8 +k
MVC 0(1,R4),CI substr(result,k,1)=ci
NOTOK LA R6,1(R6) i=i+1
B LOOPI end do i
ELOOPI STH R8,RESULT length(result)=k
MVC 0(64,R9),RESULT return(result)
BR R14 return to caller
CI DS CL1 ci [char(1)]
CJ DS CL1 cj [char(1)]
OK DS X ok [boolean]
PHRASE DS H,CL62 phrase [varchar(62)]
REMOVE DS H,CL14 remove [varchar(14)]
RESULT DS H,CL62 result [varchar(62)]
* ---- -------------------------------------------------------
YREGS
END STRIPCH
- Output:
Sh ws soul strppr. Sh took my hrt!
8080 Assembly
org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Strip a set of chracters from a string, in place.
;;; Input:
;;; DE = $-terminated string to be stripped
;;; HL = $-terminated string containing characters to strip
stripchars: push h ; Store characters to strip on stack.
mov b,d ; Copy input string pointer to BC. This will be
mov c,e ; the target pointer.
stripchr: ldax d ; Copy current character from [DE] to [BC]
stax b
cpi '$' ; Done?
jz stripdone
pop h ; Get string of characters to strip.
push h
stripsrch: mvi a,'$' ; At the end?
cmp m
jz srchdone
ldax d ; Does it match the character in the input?
cmp m
jz srchfound
inx h ; Look at next character to strip
jmp stripsrch
srchfound: dcx b ; Found: copy next character over it later.
srchdone: inx b ; Increment both pointers
inx d
jmp stripchr
stripdone: pop h ; Remove temporary variable from stack
ret ; Done
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
demo: lxi d,string ; Strip from the string,
lxi h,remove ; the characters to remove.
call stripchars
lxi d,string ; Print the result.
mvi c,9
jmp 5
string: db 'She was a soul stripper. She took my heart!$'
remove: db 'aei$'
- Output:
Sh ws soul strppr. Sh took my hrt!
8086 Assembly
bits 16
cpu 8086
section .text
org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Strip a set of characters from a string, in place.
;;; Input:
;;; DS:DI = $-terminated string to be stripped.
;;; DS:SI = $-terminated string containing chars to strip
stripchars: mov bx,di ; Copy string ptr to use as target ptr
mov dx,si ; Copy ptr to characters to strip
.char: mov al,[di] ; Copy character
mov [bx],al
cmp al,'$' ; Done?
je .done
mov si,dx ; See if character should be stripped
.search: mov ah,[si]
cmp ah,'$' ; End of characters to strip?
je .srchdone
cmp ah,al ; Does it match the current character?
je .srchfound
inc si ; Try next character
jmp .search
.srchfound: dec bx ; Found - decrement target pointer
.srchdone: inc bx ; Increment both pointers
inc di
jmp .char
.done: ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
demo: mov di,string ; Strip from the string,
mov si,remove ; the characters to remove.
call stripchars
mov dx,string ; Print the result
mov ah,9
int 21h
ret
section .data
string: db 'She was a soul stripper. She took my heart!$'
remove: db 'aei$'
- Output:
Sh ws soul strppr. Sh took my hrt!
ABC
HOW TO RETURN s stripchars chs:
PUT "" IN result
FOR c IN s:
IF c not.in chs: PUT result^c IN result
RETURN result
WRITE "She was a soul stripper. She took my heart!" stripchars "aei"/
- Output:
Sh ws soul strppr. Sh took my hrt!
Action!
PROC Strip(CHAR ARRAY text,chars,res)
BYTE i,j,size,found
CHAR c
size=0
FOR i=1 TO text(0)
DO
c=text(i) found=0
FOR j=1 TO chars(0)
DO
IF c=chars(j) THEN
found=1 EXIT
FI
OD
IF found=0 THEN
size==+1
res(size)=c
FI
OD
res(0)=size
RETURN
PROC Main()
CHAR ARRAY
text="She was a soul stripper. She took my heart!",
chars="aei", result(255)
Strip(text,chars,result)
PrintE("String to be stripped:")
PrintF("""%S""%E%E",text)
PrintE("Characters to be stripped:")
PrintF("""%S""%E%E",chars)
PrintE("Stripped string:")
PrintF("""%S""%E%E",result)
RETURN
- Output:
Screenshot from Atari 8-bit computer
String to be stripped: "She was a soul stripper. She took my heart!" Characters to be stripped: "aei" Stripped string: "Sh ws soul strppr. Sh took my hrt!"
Ada
with Ada.Text_IO;
procedure Strip_Characters_From_String is
function Strip(The_String: String; The_Characters: String)
return String is
Keep: array (Character) of Boolean := (others => True);
Result: String(The_String'Range);
Last: Natural := Result'First-1;
begin
for I in The_Characters'Range loop
Keep(The_Characters(I)) := False;
end loop;
for J in The_String'Range loop
if Keep(The_String(J)) then
Last := Last+1;
Result(Last) := The_String(J);
end if;
end loop;
return Result(Result'First .. Last);
end Strip;
S: String := "She was a soul stripper. She took my heart!";
begin -- main
Ada.Text_IO.Put_Line(Strip(S, "aei"));
end Strip_Characters_From_String;
- Output:
> ./strip_characters_from_string Sh ws soul strppr. Sh took my hrt!
Aime
text
stripchars1(data b, text w)
{
integer p;
p = b.look(0, w);
while (p < ~b) {
b.delete(p);
p += b.look(p, w);
}
b;
}
text
stripchars2(data b, text w)
{
b.drop(w);
}
integer
main(void)
{
o_text(stripchars1("She was a soul stripper. She took my heart!", "aei"));
o_newline();
o_text(stripchars2("She was a soul stripper. She took my heart!", "aei"));
o_newline();
return 0;
}
ALGOL 68
#!/usr/local/bin/a68g --script #
PROC strip chars = (STRING mine, ore)STRING: (
STRING out := "";
FOR i FROM LWB mine TO UPB mine DO
IF NOT char in string(mine[i], LOC INT, ore) THEN
out +:= mine[i]
FI
OD;
out[@LWB mine]
);
printf(($gl$,stripchars("She was a soul stripper. She took my heart!","aei")))
- Output:
Sh ws soul strppr. Sh took my hrt!
ALGOL W
begin
% returns s with the characters in remove removed %
% as all strings in Algol W are fixed length, the length of remove %
% must be specified in removeLength %
string(256) procedure stripCharacters( string(256) value s, remove
; integer value removeLength
) ;
begin
string(256) resultText;
integer tPos;
resultText := " ";
tPos := 0;
for sPos := 0 until 255 do begin
logical keepCharacter;
string(1) c;
c := s( sPos // 1 );
keepCharacter := true;
for rPos := 0 until removeLength - 1 do begin
if remove( rPos // 1 ) = c then begin
% have a character that should be removed %
keepCharacter := false;
goto endSearch
end if_have_a_character_to_remove ;
end for_rPos ;
endSearch:
if keepCharacter then begin
resultText( tPos // 1 ) := c;
tPos := tPos + 1
end if_keepCharacter
end for_sPos ;
resultText
end stripCharacters ;
% task test case %
begin
string(256) ex, stripped;
ex := "She was a soul stripper. She took my heart!";
stripped := stripCharacters( ex, "aei", 3 );
write( "text: ", ex( 0 // 64 ) );
write( " ->: ", stripped( 0 // 64 ) )
end
end.
- Output:
text: She was a soul stripper. She took my heart! ->: Sh ws soul strppr. Sh took my hrt!
Amazing Hopper
Amazing Hopper! Flavour "Jambo".
#include <jambo.h>
Main
c = ".$%#\tEste@@@ mensaje será purgado!$$$"
{"Hopper assembler:\n\n"}
{"$%#@.\t", c} str to utf8, delete char, {"\n"} print
Printnl ("\nHopper Jambo formal syntax:\n\n", Char del ( "$%#@.\t", Utf8( c ) ) )
Set ' "\nHopper Jambo Natural syntax:\n\n", "$%#@.\t", c', Get utf8, and delete char
then print with newline
End
- Output:
Hopper assembler: Este mensaje será purgado! Hopper Jambo formal syntax: Este mensaje será purgado! Hopper Jambo Natural syntax: Este mensaje será purgado!
APL
APL has a built-in function ~ ('without') that removes elements from a vector. Because a string is just a character vector, this can be used to remove characters from a string.
'She was a soul stripper. She took my heart!' ~ 'aei'
- Output:
Sh ws soul strppr. Sh took my hrt!
AppleScript
Using text item delimiters
stripChar("She was a soul stripper. She took my heart!", "aei")
on stripChar(str, chrs)
tell AppleScript
set oldTIDs to text item delimiters
set text item delimiters to characters of chrs
set TIs to text items of str
set text item delimiters to ""
set str to TIs as string
set text item delimiters to oldTIDs
end tell
return str
end stripChar
- Output:
"Sh ws soul strppr. Sh took my hrt!"
By functional composition
Without regex
(Following the Haskell contribution in reversing the argument order to the sequence more probable in a context of potential currying or partial application).
-- stripChars :: String -> String -> String
on stripChars(needles, haystack)
script notNeedles
on |λ|(x)
needles does not contain x
end |λ|
end script
intercalate("", filter(notNeedles, haystack))
end stripChars
--------------------------- TEST -------------------------
on run
stripChars("aei", "She was a soul stripper. She took my heart!")
--> "Sh ws soul strppr. Sh took my hrt!"
end run
-------------------- GENERIC FUNCTIONS -------------------
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
"Sh ws soul strppr. Sh took my hrt!"
With regex
OS X Yosemite onwards – importing the Foundation classes to use NSRegularExpression
use framework "Foundation"
--------- STRIP A SET OF CHARACTERS FROM A STRING --------
-- stripChars :: String -> String -> String
on stripChars(needles, haystack)
intercalate("", ¬
splitRegex("[" & needles & "]", haystack))
end stripChars
--------------------------- TEST -------------------------
on run
stripChars("aei", "She was a soul stripper. She took my heart!")
--> "Sh ws soul strppr. Sh took my hrt!"
end run
-------------------- GENERIC FUNCTIONS -------------------
-- splitRegex :: RegexPattern -> String -> [String]
on splitRegex(strRegex, str)
set lstMatches to regexMatches(strRegex, str)
if length of lstMatches > 0 then
script preceding
on |λ|(a, x)
set iFrom to start of a
set iLocn to (location of x)
if iLocn > iFrom then
set strPart to text (iFrom + 1) thru iLocn of str
else
set strPart to ""
end if
{parts:parts of a & strPart, start:iLocn + (length of x) - 1}
end |λ|
end script
set recLast to foldl(preceding, {parts:[], start:0}, lstMatches)
set iFinal to start of recLast
if iFinal < length of str then
parts of recLast & text (iFinal + 1) thru -1 of str
else
parts of recLast & ""
end if
else
{str}
end if
end splitRegex
-- regexMatches :: RegexPattern -> String -> [{location:Int, length:Int}]
on regexMatches(strRegex, str)
set ca to current application
set oRgx to ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬
options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) |error|:(missing value)
set oString to ca's NSString's stringWithString:str
set oMatches to oRgx's matchesInString:oString options:0 range:{location:0, |length|:oString's |length|()}
set lstMatches to {}
set lng to count of oMatches
repeat with i from 1 to lng
set end of lstMatches to range() of item i of oMatches
end repeat
lstMatches
end regexMatches
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
"Sh ws soul strppr. Sh took my hrt!"
Applesoft BASIC
100 LET S$ = "SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART!"
110 LET RM$ = "AEI"
120 GOSUB 200STRIPCHARS
130 PRINT SC$
190 END
200 REM
210 REM STRIPCHARS
220 REM
230 LET SC$ = ""
240 LET SL = LEN (S$)
250 IF SL = 0 THEN RETURN
260 FOR SI = 1 TO SL
270 LET SM$ = MID$ (S$,SI,1)
280 FOR SJ = 1 TO LEN (RM$)
290 LET SR$ = MID$ (RM$,SJ,1)
300 LET ST = SR$ < > SM$
310 IF ST THEN NEXT SJ
320 IF ST THEN SC$ = SC$ + SM$
330 NEXT SI
340 RETURN
- Output:
SH WS SOUL STRPPR. SH TOOK MY HRT!
Arturo
stripChars: function [str, chars]->
join select split str => [not? in? & split chars]
print stripChars "She was a soul stripper. She took my heart!" "aei"
- Output:
Sh ws soul strppr. Sh took my hrt!
Asymptote
string text = "She was a soul stripper. She took my heart!";
string[][] remove = {{"a",""},{"e",""},{"i",""}};
for(var i : remove)
text = replace(text, remove);
}
write(text);
AutoHotkey
MsgBox % stripchars("She was a soul stripper. She took my heart!","aei")
StripChars(string, charsToStrip){
Loop Parse, charsToStrip
StringReplace, string, string, % A_LoopField, , All
return string
}
- Output:
Sh ws soul strppr. Sh took my hrt!
AWK
#!/usr/bin/awk -f
BEGIN {
x = "She was a soul stripper. She took my heart!";
print x;
gsub(/[aei]/,"",x);
print x;
}
- Output:
She was a soul stripper. She took my heart! Sh ws soul strppr. Sh took my hrt!
BaCon
text$ = "She was a soul stripper. She took my heart!"
PRINT text$
PRINT EXTRACT$(text$, "[aei]", TRUE)
- Output:
She was a soul stripper. She took my heart! Sh ws soul strppr. Sh took my hrt!
BASIC
DECLARE FUNCTION stripchars$(src AS STRING, remove AS STRING)
PRINT stripchars$("She was a soul stripper. She took my heart!", "aei")
FUNCTION stripchars$(src AS STRING, remove AS STRING)
DIM l0 AS LONG, t AS LONG, s AS STRING
s = src
FOR l0 = 1 TO LEN(remove)
DO
t = INSTR(s, MID$(remove, l0, 1))
IF t THEN
s = LEFT$(s, t - 1) + MID$(s, t + 1)
ELSE
EXIT DO
END IF
LOOP
NEXT
stripchars$ = s
END FUNCTION
- Output:
Sh ws soul strppr. Sh took my hrt!
Chipmunk Basic
100 cls
110 print stripchars$("She was a soul stripper. She took my heart!","aei")
120 sub stripchars$(src$,remove$)
130 s$ = src$
140 for l0 = 1 to len(remove$)
150 do
160 t = instr(s$,mid$(remove$,l0,1))
170 if t then
180 s$ = left$(s$,t-1)+mid$(s$,t+1)
190 else
200 exit do
210 endif
220 loop
230 next
240 stripchars$ = s$
250 end sub
260 end
- Output:
Sh ws soul strppr. Sh took my hrt!
IS-BASIC
100 PROGRAM "Stripchr.bas"
110 PRINT STRIPCHARS$("She was a soul stripper. She took my heart!","aei")
120 DEF STRIPCHARS$(SRC$,REMOVE$)
130 LET T$=""
140 FOR I=1 TO LEN(SRC$)
150 LET L=0
160 FOR J=1 TO LEN(REMOVE$)
170 IF SRC$(I)=REMOVE$(J) THEN LET L=1:EXIT FOR
180 NEXT
190 IF L=0 THEN LET T$=T$&SRC$(I)
200 NEXT
210 LET STRIPCHARS$=T$
220 END DEF
Sinclair ZX81 BASIC
Works with 1k of RAM. Since the ZX81 character set includes neither lower case nor !, the test string is not quite identical to the one suggested in the specification.
10 LET A$="SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART."
20 LET B$="AEI"
30 GOSUB 60
40 PRINT C$
50 STOP
60 LET C$=""
70 FOR I=1 TO LEN A$
80 LET J=1
90 IF A$(I)=B$(J) THEN GOTO 130
100 LET J=J+1
110 IF J<=LEN B$ THEN GOTO 90
120 LET C$=C$+A$(I)
130 NEXT I
140 RETURN
- Output:
SH WS SOUL STRPPR. SH TOOK MY HRT.
See also: Liberty BASIC, PureBasic
BASIC256
function stripchars(texto, remove)
s = texto
for i = 1 to length(remove)
s = replace(s, mid(remove, i, 1), "", true) #true se puede omitir
next i
return s
end function
print stripchars("She was a soul stripper. She took my heart!", "aei")
BBC BASIC
PRINT FNstripchars("She was a soul stripper. She took my heart!", "aei")
END
DEF FNstripchars(A$, S$)
LOCAL I%, C%, C$
FOR I% = 1 TO LEN(S$)
C$ = MID$(S$, I%, 1)
REPEAT
C% = INSTR(A$, C$)
IF C% A$ = LEFT$(A$, C%-1) + MID$(A$, C%+1)
UNTIL C% = 0
NEXT
= A$
Output:
Sh ws soul strppr. Sh took my hrt!
BCPL
get "libhdr"
let contains(str, chr) = valof
$( for i = 1 to str%0
if str%i = chr resultis true
resultis false
$)
let stripchars(str, chars, buf) = valof
$( buf%0 := 0
for i = 1 to str%0
if ~contains(chars, str%i)
$( buf%0 := buf%0 + 1
buf%(buf%0) := str%i
$)
resultis buf
$)
let start() be
$( let buf = vec 127
writef("%S*N",
stripchars("She was a soul stripper. She took my heart!",
"aei",
buf))
$)
- Output:
Sh ws soul strppr. Sh took my hrt!
BQN
The key function here is set difference, which is (¬∘∊/⊣)
.
StripChars ← (¬∘∊/⊣)
¬∘∊/⊣
"She was a soul stripper. She took my heart!" StripChars "aei"
"Sh ws soul strppr. Sh took my hrt!"
Bracmat
This solution handles Unicode (utf-8) characters. Optimizations are: (1) the chars
string is hard-coded into the pattern before the pattern is used in the match expression, (2) the output characters are stacked (cheap) rather than appended (expensive). The result string is obtained by stringizing the stack and reversing. To make multibyte characters survive, they are reversed before being put onto the stack. A problem is that this code is negligent of diacritical marks.
( ( strip
= string chars s pat
. !arg:(?string.?chars)
& :?s
&
' ( ?
( %
: [%( utf$!sjt
& ( @($chars:? !sjt ?)
| rev$!sjt !s:?s
)
& ~
)
)
?
)
: (=?pat)
& @(!string:!pat)
| rev$(str$!s)
)
& out
$ (strip$("Аппетит приходит во время еды".веп)
);
- Output:
Атит риходит о рмя ды
Burlesque
blsq ) "She was a soul stripper. She took my heart!"{"aei"\/~[n!}f[
"Sh ws soul strppr. Sh took my hrt!"
C
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* removes all chars from string */
char *strip_chars(const char *string, const char *chars)
{
char * newstr = malloc(strlen(string) + 1);
int counter = 0;
for ( ; *string; string++) {
if (!strchr(chars, *string)) {
newstr[ counter ] = *string;
++ counter;
}
}
newstr[counter] = 0;
return newstr;
}
int main(void)
{
char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
printf("%s\n", new);
free(new);
return 0;
}
- Result:
Sh ws soul strppr. Sh took my hrt!
With table lookup
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strip(const char * str, const char *pat)
{
/* char replacement is typically done with lookup tables if
* the replacement set can be large: it turns O(m n) into
* O(m + n).
* If same replacement pattern is going to be applied to many
* strings, it's better to build a table beforehand and reuse it.
* If charset is big like unicode, table needs to be implemented
* more efficiently, say using bit field or hash table -- it
* all depends on the application.
*/
int i = 0, tbl[128] = {0};
while (*pat != '\0') tbl[(int)*(pat++)] = 1;
char *ret = malloc(strlen(str) + 1);
do {
if (!tbl[(int)*str])
ret[i++] = *str;
} while (*(str++) != '\0');
/* assuming realloc is efficient and succeeds; if not, we could
* do a two-pass, count first, alloc and strip second
*/
return realloc(ret, i);
}
int main()
{
char * x = strip("She was a soul stripper. She took my heart!", "aei");
printf(x);
free(x);
return 0;
}
Output same as above.
Gadget
Gadget C-library: Gadget C-library in Github
#include <gadget/gadget.h>
LIB_GADGET_START
Main
String r, c = ".$%#\tEste@@@ mensaje será purgado!$$$", set = "$%#@.\t";
Stack{
Store ( r, Char_del( Upper( c ), set ) );
}Stack_off
Print "Original = [%s]\nChar deleted = [%s]\n", c, r;
Free secure r,c,set;
End
- Output:
Original = [.$%# Este@@@ mensaje será purgado!$$$] Char deleted = [ESTE MENSAJE SERÁ PURGADO!]
C#
using System;
public static string RemoveCharactersFromString(string testString, string removeChars)
{
char[] charAry = removeChars.ToCharArray();
string returnString = testString;
foreach (char c in charAry)
{
while (returnString.IndexOf(c) > -1)
{
returnString = returnString.Remove(returnString.IndexOf(c), 1);
}
}
return returnString;
}
Usage:
using System;
class Program
{
static void Main(string[] args)
{
string testString = "She was a soul stripper. She took my heart!";
string removeChars = "aei";
Console.WriteLine(RemoveCharactersFromString(testString, removeChars));
}
}
- Output:
Sh ws soul strppr. Sh took my hrt!
Using Regex
:
using System;
using System.Text.RegularExpressions;
private static string RegexRemoveCharactersFromString(string testString, string removeChars)
{
string pattern = "[" + removeChars + "]";
return Regex.Replace(testString, pattern, "");
}
Alternative version using System.Span<T>
:
using System;
public static System.ReadOnlySpan<T> RemoveItems<T>(System.Span<T> toStrip, System.ReadOnlySpan<T> toRemove)
where T : System.IEquatable<T>
{
var toIndex = toStrip.Length;
for (var fromIndex = toIndex - 1; fromIndex >= 0; fromIndex--)
if (toStrip[fromIndex] is var item && !toRemove.Contains(item))
toStrip[--toIndex] = item;
return toStrip.Slice(toIndex);
}
Usage:
using System;
class Program
{
static void Main(string[] args)
{
var stripString = "She was a soul stripper. She took my heart!";
var removeString = "aei";
System.Console.WriteLine(RemoveItems<char>(stripString.ToCharArray(), removeString).ToString());
}
}
- Output:
Sh ws soul strppr. Sh took my hrt!
C++
#include <algorithm>
#include <iostream>
#include <string>
std::string stripchars(std::string str, const std::string &chars)
{
str.erase(
std::remove_if(str.begin(), str.end(), [&](char c){
return chars.find(c) != std::string::npos;
}),
str.end()
);
return str;
}
int main()
{
std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
return 0;
}
- Output:
Sh ws soul strppr. Sh took my hrt!
Clojure
(defn strip [coll chars]
(apply str (remove #((set chars) %) coll)))
(strip "She was a soul stripper. She took my heart!" "aei")
;; => "Sh ws soul strppr. Sh took my hrt!"
CLU
stripchars = proc (input, chars: string) returns (string)
result: array[char] := array[char]$[]
for c: char in string$chars(input) do
if string$indexc(c, chars) = 0 then
array[char]$addh(result, c)
end
end
return(string$ac2s(result))
end stripchars
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po,
stripchars("She was a soul stripper. She took my heart!", "aei"))
end start_up
- Output:
Sh ws soul strppr. Sh took my hrt!
COBOL
This function takes the two arguments as specified in the task. However, the result will be returned in the string that had the characters stripped from it, and the string containing the characters to strip must be null-terminated (otherwise, a table would have to be used instead).
IDENTIFICATION DIVISION.
PROGRAM-ID. Strip-Chars.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Str-Size CONSTANT 128.
LOCAL-STORAGE SECTION.
01 I PIC 999.
01 Str-Pos PIC 999.
01 Offset PIC 999.
01 New-Pos PIC 999.
01 Str-End PIC 999.
LINKAGE SECTION.
01 Str PIC X(Str-Size).
01 Chars-To-Replace PIC X(256).
PROCEDURE DIVISION USING Str BY VALUE Chars-To-Replace.
Main.
PERFORM VARYING I FROM 1 BY 1
UNTIL Chars-To-Replace (I:1) = X"00"
MOVE ZERO TO Offset
* *> Overwrite the characters to remove by left-shifting
* *> following characters over them.
PERFORM VARYING Str-Pos FROM 1 BY 1
UNTIL Str-Size < Str-Pos
IF Str (Str-Pos:1) = Chars-To-Replace (I:1)
ADD 1 TO Offset
ELSE IF Offset NOT = ZERO
COMPUTE New-Pos = Str-Pos - Offset
MOVE Str (Str-Pos:1) TO Str (New-Pos:1)
END-IF
END-PERFORM
* *> Move spaces to characters at the end that have been
* *> shifted over.
COMPUTE Str-End = Str-Size - Offset
MOVE SPACES TO Str (Str-End:Offset)
END-PERFORM
GOBACK
.
ColdFusion
<Cfset theString = 'She was a soul stripper. She took my heart!'>
<Cfset theStrip = 'aei'>
<Cfloop from="1" to="#len(theStrip)#" index="i">
<cfset theString = replace(theString, Mid(theStrip, i, 1), '', 'all')>
</Cfloop>
<Cfoutput>#theString#</Cfoutput>
Common Lisp
(defun strip-chars (str chars)
(remove-if (lambda (ch) (find ch chars)) str))
(strip-chars "She was a soul stripper. She took my heart!" "aei")
;; => "Sh ws soul strppr. Sh took my hrt!"
;; strip whitespace:
(string-trim
'(#\Space #\Newline #\Backspace #\Tab
#\Linefeed #\Page #\Return #\Rubout)
" A string ")
;; => "A string"
D
This example shows both the functional and regex solutions.
import std.stdio;
string stripchars(string s, string chars) {
import std.algorithm;
import std.conv;
return s.filter!(c => !chars.count(c)).to!string;
}
string stripchars2(string s, string chars) {
import std.regex;
return replaceAll(s, regex("[" ~ chars ~ "]"), "");
}
void main() {
string s = "She was a soul stripper. She took my heart!";
string chars = "aei";
writeln(stripchars(s, chars));
writeln(stripchars2(s, chars));
}
- Output:
Sh ws soul strppr. Sh took my hrt! Sh ws soul strppr. Sh took my hrt!
Delphi
program StripCharacters;
{$APPTYPE CONSOLE}
uses SysUtils;
function StripChars(const aSrc, aCharsToStrip: string): string;
var
c: Char;
begin
Result := aSrc;
for c in aCharsToStrip do
Result := StringReplace(Result, c, '', [rfReplaceAll, rfIgnoreCase]);
end;
const
TEST_STRING = 'She was a soul stripper. She took my heart!';
begin
Writeln(TEST_STRING);
Writeln(StripChars(TEST_STRING, 'aei'));
end.
Draco
\util.g
proc nonrec stripchars(*char str, chars, outbuf) *char:
channel input text ch_in;
channel output text ch_out;
[2]char cur = ('\e', '\e');
open(ch_in, str);
open(ch_out, outbuf);
while read(ch_in; cur[0]) do
if CharsIndex(chars, &cur[0]) = -1 then
write(ch_out; cur[0])
fi
od;
close(ch_in);
close(ch_out);
outbuf
corp
proc nonrec main() void:
[128]char buf;
writeln(
stripchars("She was a soul stripper. She took my heart!",
"aei", &buf[0]))
corp
- Output:
Sh ws soul strppr. Sh took my hrt!
EasyLang
func$ strip s$ del$ .
for c$ in strchars s$
if strpos del$ c$ <> 0
c$ = ""
.
r$ &= c$
.
return r$
.
print strip "She was a soul stripper. She took my heart!" "aei"
EchoLisp
;; using regexp /[chars]/g
(define (strip-chars string chars)
(string-replace string (string-append "/[" chars "]/g") ""))
(strip-chars "She was a soul stripper. She took my heart!" "aei")
→ "Sh ws soul strppr. Sh took my hrt!"
Elena
ELENA 4.x :
import extensions;
import extensions'text;
import system'routines;
public program()
{
var testString := "She was a soul stripper. She took my heart!";
var removeChars := "aei";
console.printLine(testString.filterBy::(ch => removeChars.indexOf(0, ch) == -1).summarize(new StringWriter()))
}
- Output:
Sh ws soul strppr. Sh took my hrt!
Elixir
The easiest solution would be to use replace from the String module, which takes a Regex.
str = "She was a soul stripper. She took my heart!"
String.replace(str, ~r/[aei]/, "")
# => Sh ws soul strppr. Sh took my hrt!
To get the desired interface, we just have to dynamically construct the Regex:
defmodule RC do
def stripchars(str, chars) do
String.replace(str, ~r/[#{chars}]/, "")
end
end
str = "She was a soul stripper. She took my heart!"
RC.stripchars(str, "aei")
# => Sh ws soul strppr. Sh took my hrt!
Emacs Lisp
(defun stripchars (s chars)
(seq-into
(seq-filter (lambda (x) (not (seq-contains chars x))) s)
'string))
(stripchars "She was a soul stripper. She took my heart!" "aei")
- Output:
"Sh ws soul strppr. Sh took my hrt!"
Erlang
The function is created in the shell. A module would be over engineering.
- Output:
4> F = fun(To_stripp, Strip_with) -> lists:filter( fun(C) -> not lists:member(C, Strip_with) end, To_stripp ) end. #Fun<erl_eval.12.111823515> 5> F("She was a soul stripper. She took my heart!", "aei"). "Sh ws soul strppr. Sh took my hrt!"
Euphoria
The includes use Euphoria 4 standard library files.
A sequence called originalString holds the text to be converted.
The puts
function is for console output.
The work of this task is done by the transmute
function; this function takes parameters separated by commas. Here it uses 3 parameters, up to 5, the other two are optional and aren't put in this time.
The transmute
function's usage and examples can be searched for in the official Euphoria 4.0.0+ manual. Euphoria object identifiers (names) are case sensitive but don't need to be in a particular case to be recognized as an object type.
include std\sequence.e
include std\console.e
sequence originalString = "She was a soul stripper. She took my heart!"
puts(1,"Before : " & originalString & "\n")
originalString = transmute(originalString, {{} , "a", "e", "i"}, {{} , "", "", ""})
puts(1,"After : " & originalString & "\n")
any_key()
- Output:
Before : She was a soul stripper. She took my heart! After : Sh ws soul strppr. Sh took my hrt! Press Any Key to continue...
Excel
LAMBDA
Binding the name exceptChars to the following lambda expression in the Name Manager of the Excel WorkBook:
(See LAMBDA: The ultimate Excel worksheet function)
exceptChars
=LAMBDA(excluded,
LAMBDA(src,
CONCAT(
FILTERP(
LAMBDA(c,
ISERROR(
FIND(c, excluded, 1)
)
)
)(
CHARSROW(src)
)
)
)
)
and also assuming the following generic bindings in the Name Manager for the WorkBook:
CHARSROW
=LAMBDA(s,
MID(s,
SEQUENCE(1, LEN(s), 1, 1),
1
)
)
FILTERP
=LAMBDA(p,
LAMBDA(xs,
FILTER(xs, p(xs))
)
)
- Output:
fx | =exceptChars(A2)(B1) | ||
---|---|---|---|
A | B | ||
1 | She was a soul stripper. She took my heart! | ||
2 | aei | Sh ws soul strppr. Sh took my hrt! |
F#
let stripChars text (chars:string) =
Seq.fold (
fun (s:string) c -> s.Replace(c.ToString(),"")
) text chars
printfn "%s" (stripChars "She was a soul stripper. She took my heart!" "aei")
- Output:
Sh ws soul strppr. Sh took my hrt!
Factor
without
Example:
USE: sets
"She was a soul stripper. She took my heart!" "aei" without print
- Output:
Sh ws soul strppr. Sh took my hrt!
Forth
Forth is a low level language that is extended to solve your problem. Here we add APPEND-CHAR to the language and use it built the new string character by character in a memory buffer called PAD. PAD is a standard Forth word. SCAN is common in most Forth systems and is typically coded in Forth assembler
: append-char ( char str -- ) dup >r count dup 1+ r> c! + c! ; \ append char to a counted string
: strippers ( -- addr len) s" aeiAEI" ; \ a string literal returns addr and length
: stripchars ( addr1 len1 addr2 len2 -- PAD len )
0 PAD c! \ clear the PAD buffer
bounds \ calc loop limits for addr2
DO
2dup I C@ ( -- addr1 len1 addr1 len1 char)
scan nip 0= \ scan for char in addr1, test for zero
IF \ if stack = true (ie. NOT found)
I c@ PAD append-char \ fetch addr2 char, append to PAD
THEN \ ...then ... continue the loop
LOOP
2drop \ we don't need STRIPPERS now
PAD count ; \ return PAD address and length
Test at the forth console
strippers s" She was a soul stripper. She took my heart!" stripchars cr type Sh ws soul strppr. Sh took my hrt! ok
Shorter version, using ]] [[ macros
This shorter version removes creating a new string and prints the "stripped" string immediately. The macro called '?exit' speeds up the '.stripped' print loop by compiling its code inside the loop.
: ?exit ( c1 c2 -- ) ]] = if drop unloop exit then [[ ; immediate
: .stripped ( a u c -- ) -rot bounds ?do dup i c@ ?exit loop emit ;
: stripchars ( a1 u1 a2 u2 -- ) bounds ?do 2dup i c@ .stripped loop 2drop ;
: "aei" s" aei" ;
\ usage: "aei" s" She was a soul stripper. She took my heart!" stripchars
Fortran
elemental subroutine strip(string,set)
character(len=*), intent(inout) :: string
character(len=*), intent(in) :: set
integer :: old, new, stride
old = 1; new = 1
do
stride = scan( string( old : ), set )
if ( stride > 0 ) then
string( new : new+stride-2 ) = string( old : old+stride-2 )
old = old+stride
new = new+stride-1
else
string( new : ) = string( old : )
return
end if
end do
end subroutine strip
Note: Since strip is an elemental subroutine, it can be called with arrays of strings as well.
FreeBASIC
' FB 1.05.0 Win64
Function stripChars(s As Const String, chars As Const String) As String
If s = "" Then Return ""
Dim count As Integer = 0
Dim strip(0 To Len(s) - 1) As Boolean
For i As Integer = 0 To Len(s) - 1
For j As Integer = 0 To Len(chars) - 1
If s[i] = chars[j] Then
count += 1
strip(i) = True
Exit For
End If
Next j
Next i
Dim buffer As String = Space(Len(s) - count)
count = 0
For i As Integer = 0 To Len(s) - 1
If Not Strip(i) Then
buffer[count] = s[i]
count += 1
End If
Next
Return buffer
End Function
Dim s As String = "She was a soul stripper. She took my heart!"
Dim chars As String = "aei"
Print stripChars(s, chars)
Print
Print "Press any key to quit"
Sleep
- Output:
Sh ws soul strppr. Sh took my hrt!
Frink
stripchars[str, remove] :=
{
set = toSet[chars[remove]]
return char[remove[char[str], {|c, set| set.contains[c]}, set]]
}
println[stripchars["She was a soul stripper. She took my heart!","aei"]]
- Output:
Sh ws soul strppr. Sh took my hrt!
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Test case
FutureBasic
window 1, @"Strip a set of characters from a string"
local fn StringByStrippingCharacters( string as CFStringRef, chrs as CFStringRef ) as CFStringRef
end fn = fn ArrayComponentsJoinedByString( fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetWithCharactersInString( chrs ) ), @"" )
CFStringRef string, chrs
string = @"She was a soul stripper. She took my heart!"
chrs = @"aei"
print string
print fn StringByStrippingCharacters( string, chrs )
HandleEvents
- Output:
She was a soul stripper. She took my heart! Sh ws soul strppr. Sh took my hrt!
Gambas
Click this link to run this code
Public Sub Main()
Print StripChars("She was a soul stripper. She took my heart!", "aei")
End
'_____________________________________________________________________
Public Sub StripChars(sText As String, sRemove As String) As String
Dim siCount As Short
For siCount = 1 To Len(sRemove)
sText = Replace(sText, Mid(sRemove, siCount, 1), "")
Next
Return sText
End
Output:
Sh ws soul strppr. Sh took my hrt!
Go
package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
- Output:
Sh ws soul strppr. Sh took my hrt!
Groovy
Solution:
def stripChars = { string, stripChars ->
def list = string as List
list.removeAll(stripChars as List)
list.join()
}
Test:
println (stripChars('She was a soul stripper. She took my heart!', 'aei'))
- Output:
Sh ws soul strppr. Sh took my hrt!
Haskell
I decided to make the string the second argument and the characters the first argument, because it is more likely for someone to partially apply the characters to be stripped (making a function that strips certain characters), than the string.
stripChars :: String -> String -> String
stripChars = filter . flip notElem
- Testing in GHCI:
> stripChars "aei" "She was a soul stripper. She took my heart!" "Sh ws soul strppr. Sh took my hrt!"
Icon and Unicon
The following works in both languages:
procedure main(A)
cs := \A[1] | 'aei' # argument is set of characters to strip
every write(stripChars(!&input, cs)) # strip all input lines
end
procedure stripChars(s,cs)
ns := ""
s ? while ns ||:= (not pos(0), tab(upto(cs)|0)) do tab(many(cs))
return ns
end
- Sample runs:
->strip She was a soul stripper. She took my heart! Sh ws soul strppr. Sh took my hrt! Aardvarks are ant eaters. Ardvrks r nt trs. ->strip AEIOUaeiou Aardvarks are ant eaters. rdvrks r nt trs. ->
Insitux
(function strip from what
(remove (to-vec what) from))
(strip "She was a soul stripper. She took my heart!" "aei")
;returns "Sh ws soul strppr. Sh took my hrt!"
J
Solution:
The dyadic primitive -.
(Less) is probably the simplest way to solve this task.
- Example Usage:
'She was a soul stripper. She took my heart!' -. 'aei'
Sh ws soul strppr. Sh took my hrt!
Java
The most basic approach is to use the String.replace method.
String stripCharacters(String string, String characters) {
for (char character : characters.toCharArray())
string = string.replace(String.valueOf(character), "");
return string;
}
You could also use a StringBuilder which provides a deleteCharAt method.
String stripCharacters(String string, String characters) {
StringBuilder stripped = new StringBuilder(string);
/* traversing the string backwards is necessary to avoid collision */
for (int index = string.length() - 1; index >= 0; index--) {
if (characters.contains(String.valueOf(string.charAt(index))))
stripped.deleteCharAt(index);
}
return stripped.toString();
}
You could use the String.replaceAll method, which takes a regular expression as it's first argument.
static String stripCharacters(String string, String characters) {
/* be sure to 'quote' the 'characters' to avoid pattern collision */
characters = Pattern.quote(characters);
string = string.replaceAll("[%s]".formatted(characters), "");
return string;
}
These will all produce the following string.
Sh ws soul strppr. Sh took my hrt!
JavaScript
ES5
function stripchars(string, chars) {
return string.replace(RegExp('['+chars+']','g'), '');
}
ES6
Reversing the order of the arguments, to simplify any currying:
(() => {
'use strict';
// stripChars :: String -> String -> String
const stripChars = (strNeedles, strHayStack) =>
strHayStack.replace(RegExp(`[${strNeedles}]`, 'g'), '');
// GENERIC FUNCTION
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
// TEST FUNCTION
const noAEI = curry(stripChars)('aeiAEI');
// TEST
return noAEI('She was a soul stripper. She took my heart!');
// 'Sh ws soul strppr. Sh took my hrt!'
})();
- Output:
'Sh ws soul strppr. Sh took my hrt!'
Alternatively, we could also do this without a regex:
(() => {
'use strict';
// stripChars :: String -> String -> String
const stripChars = (strNeedles, strHayStack) =>
strHayStack.split('')
.filter(x => !elem(x, strNeedles))
.join('');
// GENERIC FUNCTIONS
// elem :: Eq a => a -> [a] -> Bool
const elem = (x, xs) => xs.indexOf(x) !== -1;
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
// TEST FUNCTION
const noAEI = curry(stripChars)('aeiAEI');
// TEST
return noAEI('She was a soul stripper. She took my heart!');
// 'Sh ws soul strppr. Sh took my hrt!'
})();
- Output:
'Sh ws soul strppr. Sh took my hrt!'
Joy
DEFINE stripchars == [in not] cons filter.
"She was a soul stripper. She took my heart!" "aei" stripchars.
- Output:
"Sh ws soul strppr. Sh took my hrt!"
jq
def stripchars(string; banish):
(string | explode) - (banish | explode) | implode;
Note: In jq, it would be more idiomatic to define the function as a filter:
def stripchars(banish):
explode - (banish | explode) | implode;
In this case, we would write:
"She was a soul stripper. She took my heart!" | stripchars("aei")
Julia
stripChar = (s, r) -> replace(s, Regex("[$r]") => "")
- Output:
> stripChar("She was a soul stripper. She took my heart!", "aei") Sh ws soul strppr. Sh took my hrt!
K
"She was a soul stripper. She took my heart!" ^ "aei"
- Output:
"Sh ws soul strppr. Sh took my hrt!"
Kotlin
fun stripChars(s: String, r: String) = s.filter { it !in r }
fun main(args: Array<String>) {
println(stripChars("She was a soul stripper. She took my heart!", "aei"))
}
- Output:
Sh ws soul strppr. Sh took my hrt!
Lambdatalk
Text substitutions are easy to process directly using regular expressions :
{S.replace (a|e|i)
by // nothing
in She was a soul stripper. She took my heart!}
-> Sh ws soul strppr. Sh took my hrt!
and can be wrapped inside a fuction:
{def word2rex
{def word2rex.r
{lambda {:w}
{if {W.empty? {W.rest :w}}
then {W.first :w})
else {W.first :w}|{word2rex.r {W.rest :w}}}}}
{lambda {:w :s}
{S.replace ({word2rex.r :w} by in :s}}}
-> word2rex
{word2rex aei
She was a soul stripper. She took my heart!}
-> Sh ws soul strppr. Sh took my hrt!
Lasso
define stripper(in::string,destroy::string) => {
with toremove in #destroy->values do => {
#in->replace(#toremove,'')
}
return #in
}
stripper('She was a soul stripper. She took my heart!','aei')
- Output:
Sh ws soul strppr. Sh took my hrt!
Liberty BASIC
Print stripchars$("She was a soul stripper. She took my heart!", "aei", 1)
End
Function stripchars$(strip$, chars$, num)
For i = 1 To Len(strip$)
If Mid$(strip$, i, 1) <> Mid$(chars$, num, 1) Then
stripchars$ = (stripchars$ + Mid$(strip$, i, 1))
End If
Next i
If (num <= Len(chars$)) Then stripchars$ = stripchars$(stripchars$, chars$, (num + 1))
End Function
LiveCode
function stripChars str charlist
local strstripped
put str into strstripped
repeat for each char c in charlist
replace c with empty in strstripped
end repeat
return strstripped
end stripChars
Test
command teststripchars
put stripchars("She was a soul stripper. She took my heart!","aei")
end teststripchars
Output
Sh ws soul strppr. Sh took my hrt!
Logo
to strip :string :chars
output filter [not substringp ? :chars] :string
end
print strip "She\ was\ a\ soul\ stripper.\ She\ took\ my\ heart! "aei
bye
- Output:
Sh ws soul strppr. Sh took my hrt!
Lua
function stripchars(str, chrs)
local s = str:gsub("["..chrs:gsub("%W","%%%1").."]", '')
return s
end
print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) )
--> Sh ws soul strppr. Sh took my hrt!
print( stripchars( "She was a soul stripper. She took my heart!", "a-z" ) )
--> She ws soul stripper. She took my hert!
Maple
with(StringTools):
Remove(c->Has("aei",c), "She was a soul stripper. She took my heart!");
Output:
"Sh ws soul strppr. Sh took my hrt!"
Mathematica /Wolfram Language
stripchars[a_,b_]:=StringReplace[a,(#->"")&/@Characters[b]]
stripchars["She was a soul stripper. She took my heart!","aei"]
->Sh ws soul strppr. Sh took my hrt!
MATLAB / Octave
function str = stripchars(str, charlist)
% MATLAB after 2016b: str = erase(str, charlist);
str(ismember(str, charlist)) = '';
- Output:
>> stripchars('She was a soul stripper. She took my heart!','aei') ans = Sh ws soul strppr. Sh took my hrt!
Nanoquery
def stripchars(string, chars)
for char in chars
string = string.replace(char, "")
end
return string
end
Nemerle
StripChars( text : string, remove : string ) : string
{
def chuck = Explode(remove);
Concat( "", Split(text, chuck))
}
NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols
say stripchars("She was a soul stripper. She took my heart!", "aei")
return
method stripchars(haystack, chs) public static
loop c_ = 1 to chs.length
needle = chs.substr(c_, 1)
haystack = haystack.changestr(needle, '')
end c_
return haystack
NewLISP
(let (sentence "She was a soul stripper. She took my heart!")
(replace "[aei]" sentence "" 0))
Nim
import strutils
echo "She was a soul stripper. She took my heart!".split({'a','e','i'}).join()
echo "She was a soul stripper. She took my heart!".multiReplace(
("a", ""),
("e", ""),
("i", "")
)
# And another way using module "sequtils".
import sequtils
echo "She was a soul stripper. She took my heart!".filterIt(it notin "aei").join()
- Output:
Sh ws soul strppr. Sh took my hrt! Sh ws soul strppr. Sh took my hrt! Sh ws soul strppr. Sh took my hrt!
Objective-C
@interface NSString (StripCharacters)
- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars;
@end
@implementation NSString (StripCharacters)
- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars {
return [[self componentsSeparatedByCharactersInSet:chars] componentsJoinedByString:@""];
}
@end
- To use:
NSString *aString = @"She was a soul stripper. She took my heart!";
NSCharacterSet* chars = [NSCharacterSet characterSetWithCharactersInString:@"aei"];
// Display the NSString.
NSLog(@"%@", [aString stripCharactersInSet:chars]);
OCaml
let stripchars s cs =
let len = String.length s in
let res = Bytes.create len in
let rec aux i j =
if i >= len
then Bytes.to_string (Bytes.sub res 0 j)
else if String.contains cs s.[i] then
aux (succ i) (j)
else begin
Bytes.set res j s.[i];
aux (succ i) (succ j)
end
in
aux 0 0
- Testing in the toplevel:
# stripchars "She was a soul stripper. She took my heart!" "aei" ;; - : string = "Sh ws soul strppr. Sh took my hrt!"
Oforth
String method: stripChars(str) #[ str include not ] self filter ;
"She was a soul stripper. She took my heart!" stripChars("aei") println
- Output:
Sh ws soul strppr. Sh took my hrt!
PARI/GP
GP should not be used for string manipulation. A good solution to this problem would probably involve system("perl -e
...
stripchars(s, bad)={
bad=Set(Vec(Vecsmall(bad)));
s=Vecsmall(s);
my(v=[]);
for(i=1,#s,if(!setsearch(bad,s[i]),v=concat(v,s[i])));
Strchr(v)
};
stripchars("She was a soul stripper. She took my heart!","aei")
Pascal
See Delphi
PascalABC.NET
function StripChars(s,chars: string): string
:= s.Where(c -> c not in chars).JoinToString;
begin
Print(StripChars('She was a soul stripper. She took my heart!','aei'));
end.
- Output:
Sh ws soul strppr. Sh took my hrt!
Perl
Note: this example uses a regular expression character class. Certain characters, like hyphens and brackets, may need to be escaped.
sub stripchars {
my ($s, $chars) = @_;
$s =~ s/[$chars]//g;
return $s;
}
print stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
- Output:
Sh ws soul strppr. Sh took my hrt!
Another good option for stripping characters is to use the tr///
operator. This option is very efficient when the set of characters to strip is fixed at compile time, because tr///
is specifically designed for transforming and deleting characters. Note that hyphens also have special meaning in this case.
$str =~ tr/aei//d;
Since the characters used for tr///
must be fixed at compile time, unfortunately, it requires the use of an eval
to do this generally for any set of characters provided at runtime:
sub stripchars {
my ($s, $chars) = @_;
eval("\$s =~ tr/$chars//d;");
return $s;
}
Phix
?filter("She was a soul stripper. She took my heart!","out","aei")
- Output:
"Sh ws soul strppr. Sh took my hrt!"
PHP
<?php
function stripchars($s, $chars) {
return str_replace(str_split($chars), "", $s);
}
echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
?>
- Output:
Sh ws soul strppr. Sh took my hrt!
Picat
List comprehension
stripchars(String, Chars) = [C : C in String, not(membchk(C,Chars))].
Recursion
stripchars2(String,Chars, Res) =>
stripchars2(String, Chars, [], Res).
stripchars2([], _Chars, Res, Res).
stripchars2([H|T], Chars, Res1, Res) :-
membchk(H,Chars),
stripchars2(T, Chars, Res1, Res).
stripchars2([H|T], Chars, Res1, [H|Res]) :-
stripchars2(T, Chars, Res1, Res).
Test
go =>
S = "She was a soul stripper. She took my heart!",
println(stripchars(S, "aei")),
stripchars2(S, "aei", S2),
println(S2),
nl.
- Output:
Sh ws soul strppr. Sh took my hrt! Sh ws soul strppr. Sh took my hrt!
PicoLisp
(de strDiff (Str1 Str2)
(pack (diff (chop Str1) (chop Str2))) )
- Output:
: (strDiff "She was a soul stripper. She took my heart!" "aei") -> "Sh ws soul strppr. Sh took my hrt!"
PL/I
strip_chars: procedure (text, chars) returns (character (100) varying);
declare text character (*) varying, chars character (*) varying;
declare out_text character (100);
declare ch character (1);
declare (i, j) fixed binary;
j = 0;
do i = 1 to length(text);
ch = substr(text, i, 1);
if index(chars, ch) = 0 then
do; j = j + 1; substr(out_text, j, 1) = ch; end;
end;
return (substr(out_text, 1, j) );
end strip_chars;
PL/M
100H:
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PRINT: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
DECLARE TRUE LITERALLY '0FFH', FALSE LITERALLY '0';
/* SEE IF STRING CONTAINS CHARACTER */
CONTAINS: PROCEDURE(STR, CHR) BYTE;
DECLARE STR ADDRESS, (SCH BASED STR, CHR) BYTE;
DO WHILE SCH <> '$';
IF SCH = CHR THEN RETURN TRUE;
STR = STR + 1;
END;
RETURN FALSE;
END CONTAINS;
/* STRIP CHARACTERS FROM A STRING */
STRIP$CHARS: PROCEDURE(STR, CHARS, OUTBUF);
DECLARE (STR, CHARS, OUTBUF) ADDRESS;
DECLARE (IN$CH BASED STR, OUT$CH BASED OUTBUF) BYTE;
DO WHILE IN$CH <> '$';
IF NOT CONTAINS(CHARS, IN$CH) THEN DO;
OUT$CH = IN$CH;
OUTBUF = OUTBUF + 1;
END;
STR = STR + 1;
END;
OUT$CH = '$';
END STRIP$CHARS;
/* TEST */
DECLARE BUF (128) ADDRESS;
/* 8080 PL/M DOES NOT SUPPORT LOWERCASE OR EXCLAMATION MARK */
CALL STRIP$CHARS(
.'SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART.$',
.'AEI$',
.BUF);
CALL PRINT(.BUF);
CALL EXIT;
EOF
- Output:
SH WS SOUL STRPPR. SH TOOK MY HRT.
Powershell
Powershell have replace operator that by will replace a regex pattern with a given string:
'She was a soul stripper. She took my heart!' -replace '[aei]', ''
Sh ws soul strppr. Sh took my hrt!
Prolog
Works with SWI-Prolog and module lambda.pl written by Ulrich Neumerkel found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl .
:- use_module(library(lambda)).
stripchars(String, Exclude, Result) :-
exclude(\X^(member(X, Exclude)), String, Result1),
string_to_list(Result, Result1).
- Output:
?- stripchars("She was a soul stripper. She took my heart!","aei", R). R = "Sh ws soul strppr. Sh took my hrt!".
alternative version using DCG strings
:- system:set_prolog_flag(double_quotes,chars) .
%! strip_chars(SOURCEz0,SETz0,TARGETz)
%
% `TARGETz` is `SOURCEz0` but with any of the characters in `SETz0` removed .
strip_chars(SOURCEz0,SETz0,TARGETz)
:-
prolog:phrase(strip_chars(SOURCEz0,SETz0),TARGETz)
.
strip_chars([],_SETz0_) --> ! .
strip_chars([SOURCE0|SOURCEz0],SETz0)
-->
{ \+ \+ lists:member(SOURCE0,SETz0) } ,
! ,
strip_chars(SOURCEz0,SETz0)
.
strip_chars([SOURCE0|SOURCEz0],SETz0)
-->
[SOURCE0] ,
strip_chars(SOURCEz0,SETz0)
.
- Output:
?- strip_chars("She was a soul stripper. She took my heart!","aei",Rs) . Rs = ['S', h, ' ', w, s, ' ', ' ', s, o, u, l, ' ', s, t, r, p, p, r, '.', ' ', 'S', h, ' ', t, o, o, k, ' ', m, y, ' ', h, r, t, !].
PureBasic
PureBasic uses a single (for ASCII) or a two-byte (for Unicode) null to signal the end of a string. Nulls are thus excluded from the allowable characters to strip as they can't be included in a PureBasic string.
Procedure.s stripChars(source.s, charsToStrip.s)
Protected i, *ptrChar.Character, length = Len(source), result.s
*ptrChar = @source
For i = 1 To length
If Not FindString(charsToStrip, Chr(*ptrChar\c))
result + Chr(*ptrChar\c)
EndIf
*ptrChar + SizeOf(Character)
Next
ProcedureReturn result
EndProcedure
If OpenConsole()
PrintN(stripChars("She was a soul stripper. She took my heart!", "aei"))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
- Output:
Sh ws soul strppr. Sh took my hrt!
Python
Not using regular expressions
>>> def stripchars(s, chars):
... return s.translate(None, chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
>>> import string
>>> def stripchars(s, chars):
... return s.translate(string.maketrans("", ""), chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
Implemented manually:
>>> def stripchars(s, chars):
... return "".join(c for c in s if c not in chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
Using regular expressions
>>> import re
>>> def stripchars(s, chars):
return re.sub('[%s]+' % re.escape(chars), '', s)
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
>>>
Quackery
[ $ "" swap witheach [ upper join ] ] is upper$ ( $ --> $ )
[ $ "" swap witheach [ lower join ] ] is lower$ ( $ --> $ )
[ 0 swap witheach [ bit | ] ] is ->set ( [ --> s )
[ bit & not ] is !in ( s c --> b )
[ $ "" unrot
upper$ dup lower$ join ( omit this line for case-sensitive )
->set swap witheach
[ 2dup !in iff
[ swap dip join ]
else drop ] drop ] is strip$ ( $ $ --> $ )
$ "One is never alone with a rubber duck." dup echo$ cr
$ "EIU" strip$ echo$ cr
- Output:
One is never alone with a rubber duck. On s nvr alon wth a rbbr dck.
Racket
#lang racket
;; Using list operations
(define (stripchars1 text chars)
(list->string (remove* (string->list chars) (string->list text))))
;; Using a regexp
;; => will be broken if chars have "-" or "]" or "\\"
(define (stripchars2 text chars)
(regexp-replace* (~a "[" chars "]+") text ""))
Raku
(formerly Perl 6)
sub strip_chars ( $s, $chars ) {
return $s.trans( $chars.comb X=> '' );
}
say strip_chars( 'She was a soul stripper. She took my heart!', 'aei' );
- Output:
Sh ws soul strppr. Sh took my hrt!
Red
stripchars: func [str chars] [trim/with str chars]
stripchars "She was a soul stripper. She took my heart!" "aei"
Refal
$ENTRY Go {
= <Prout <Strip ('aei') 'She was a soul stripper. She took my heart!'>>;
};
Strip {
(e.Chs) = ;
(e.Chs) s.C e.S, e.Chs: e.1 s.C e.2 = <Strip (e.Chs) e.S>;
(e.Chs) s.C e.S = s.C <Strip (e.Chs) e.S>;
};
- Output:
Sh ws soul strppr. Sh took my hrt!
REXX
version 1
In the REXX language, strip usually means to remove leading and/or trailing characters from a string (most often, blanks).
/*REXX program removes a list of characters from a string (the haystack). */
say stripChars('She was a soul stripper. She took my heart!', "iea") /*elide: iea */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
stripChars: procedure; parse arg haystack, remove
do j=1 for length(remove)
haystack=changestr( substr( remove, j, 1), haystack, '')
end /*j*/
return haystack
Some older REXXes don't have a changestr BIF, so one is included here ───► CHANGESTR.REX.
- output :
Sh ws soul strppr. Sh took my hrt!
version 2
Using recursion:
/* REXX */
say StripChars('She was a soul stripper. She took my heart!','iea')
exit 0
StripChars: procedure
parse arg strng,remove
removepos=Verify(strng,remove,'MATCH')
if removepos=0 then return strng
parse value strng with strng =(removepos) +1 rest
return strng || StripChars(rest,remove)
- Output:
Sh ws soul strppr. Sh took my hart!rt!
version 3
This works on all Rexxes.
(Except for R4 and ROO at the least, there may be others.)
/* REXX ***************************************************************
* If source and stripchars don't contain a hex 00 character, this works
* 06.07.2012 Walter Pachl
* 19.06.2013 -"- space(result,0) -> space(result,0,' ')
* space(result,0) removes WHITESPACE not only blanks
**********************************************************************/
Say 'Sh ws soul strppr. Sh took my hrt! -- expected'
Say stripchars("She was a soul stripper. She took my heart!","aei")
Exit
stripchars: Parse Arg string,stripchars
result=translate(string,'00'x,' ') /* turn blanks into '00'x */
result=translate(result,' ',stripchars) /* turn stripchars into ' ' */
result=space(result,0,' ') /* remove all blanks */
Return translate(result,' ','00'x) /* '00'x back to blanks */
version 4
Another neat (?) one No x00 restriction and no changestr
stripchars: Procedure
Parse Arg i,s /* get input and chars to be removed */
o='' /* initialize result */
Do While i\=='' /* loop through input */
Parse Var i c +1 i /* get one character */
If pos(c,s)=0 Then /* it's not to be removed */
o=o||c /* append it to the result */
End
Return o /* return the result */
Ring
aList = "She was a soul stripper. She took my heart!"
bList = "aei"
see aList + nl
see stripChars(aList,bList)
func stripChars cList, dList
for n = 1 to len(dList)
cList = substr(cList,dList[n],"") + nl
next
return cList
RPL
≪ → string out ≪ "" 1 string SIZE FOR j string j DUP SUB IF out OVER POS THEN DROP ELSE + END NEXT ≫ ≫ 'STRIP' STO
- Input:
"She was a soul stripper. She took my heart!" "aei" STRIP
- Input:
1: "Sh ws soul strppr. Sh took my hrt!"
Ruby
"She was a soul stripper. She took my heart!".delete("aei") # => "Sh ws soul strppr. Sh took my hrt!"
Run BASIC
function stripchars(texto, remove)
s = texto
for i = 1 to length(remove)
s = replace(s, mid(remove, i, 1), "", true)
next i
return s
end function
Rust
Naive Implementation:
fn strip_characters(original : &str, to_strip : &str) -> String {
let mut result = String::new();
for c in original.chars() {
if !to_strip.contains(c) {
result.push(c);
}
}
result
}
Functional Implementation:
fn strip_characters(original : &str, to_strip : &str) -> String {
original.chars().filter(|&c| !to_strip.contains(c)).collect()
}
Either can be executed thusly:
fn main() {
println!("{}", strip_characters("She was a soul stripper. She took my heart!", "aei"));
}
SAS
This code will write the resulting string to the log:
%let string=She was a soul stripper. She took my heart!;
%let chars=aei;
%let stripped=%sysfunc(compress("&string","&chars"));
%put &stripped;
Log:
Sh ws soul strppr. Sh took my hrt!
S-BASIC
rem - strip unwanted characters from a string
function strip(s, unwanted = string) = string
var i = integer
var outstr = string
var ch = char
outstr = ""
for i = 1 to len(s)
ch = mid(s, i, 1)
if instr(1, unwanted, ch) = 0 then
outstr = outstr + ch
next i
end = outstr
rem - exercise the routine
print strip("She was a soul stripper. She took my heart!","aei")
end
- Output:
Sh ws soul strppr. Sh took my hrt!
Scala
def stripChars(s:String, ch:String)= s filterNot (ch contains _)
stripChars("She was a soul stripper. She took my heart!", "aei")
// => Sh ws soul strppr. Sh took my hrt!
Scheme
Two approaches are given here. The first is in plain Scheme, and implements a loop to remove the characters. The second uses the SRFI libraries to create a character set and delete those characters from the string.
(import (scheme base)
(scheme write)
(only (srfi 13) string-delete)
(only (srfi 14) ->char-set))
;; implementation in plain Scheme
(define (strip-chars str chars)
(let ((char-list (string->list chars)))
(define (do-strip str-list result)
(cond ((null? str-list)
(reverse result))
((member (car str-list) char-list char=?)
(do-strip (cdr str-list) result))
(else
(do-strip (cdr str-list) (cons (car str-list) result)))))
(list->string
(do-strip (string->list str) '()))))
(display (strip-chars "She was a soul stripper. She took my heart!" "aei"))
(newline)
;; using functions in SRFI 13 and SRFI 14
(define (strip-chars2 str chars)
(string-delete (->char-set chars) str))
(display (strip-chars2 "She was a soul stripper. She took my heart!" "aei"))
(newline)
- Output:
Sh ws soul strppr. Sh took my hrt! Sh ws soul strppr. Sh took my hrt!
ScriptBasic
str1 = "She was a soul stripper. She took my heart!"
rmv = "aei"
FOR i = 1 TO LEN(rmv)
str1 = REPLACE(str1, MID(rmv, i, 1), "")
NEXT
PRINT str1,"\n"
Sed
Using echo and piping it through a sed filter:
#!/bin/bash
strip_char()
{
echo "$1" | sed "s/[$2]//g"
}
Seed7
$ include "seed7_05.s7i";
const func string: stripchars (in string: mainStri, in string: charList) is func
result
var string: strippedStri is "";
local
var char: ch is ' ';
begin
strippedStri := mainStri;
for ch range charList do
strippedStri := replace(strippedStri, str(ch), "");
end for;
end func;
const proc: main is func
begin
writeln(stripchars("She was a soul stripper. She took my heart!", "aei"));
end func;
- Output:
Sh ws soul strppr. Sh took my hrt!
SETL
program strip_chars;
print(strip("She was a soul stripper. She took my heart!", "aei"));
proc strip(s, chs);
return +/[c : c in s | not c in chs];
end proc;
end program;
- Output:
Sh ws soul strppr. Sh took my hrt!
Sidef
func stripchars(str, char_list) {
str.tr(char_list, "", "d");
}
or:
func stripchars(str, char_list) {
str.chars.grep {|c| !char_list.contains(c)}.join;
}
Calling the function:
say stripchars("She was a soul stripper. She took my heart!", "aei");
- Output:
Sh ws soul strppr. Sh took my hrt!
Slope
This example ignores all type/error checking in favor of brevity and assumes two strings will be given. A solution could also likely be crafted using regex-replace or string-replace.
(define strip-chars (lambda (str chrs)
(define chr-list (map (lambda (ch) (string->rune ch)) (string->list chrs)))
(list->string
(filter
(lambda (ch) (not (member? chr-list (string->rune ch))))
(string->list str)))))
(display (strip-chars "She was a soul stripper. She took my heart!" "aei"))
- Output:
Sh ws soul strppr. Sh took my hrt!
Smalltalk
| stripChars |
stripChars := [ :string :chars |
string reject: [ :c | chars includes: c ] ].
stripChars
value: 'She was a soul stripper. She took my heart!'
value: 'aei'.
"'Sh ws soul strppr. Sh took my hrt!'"
SNOBOL4
Note: "strip" is a function, its argument, the label of its first executed line, and its returned value.
DEFINE("strip(strip,c)") :(strip_end)
strip strip ANY(c) = :S(strip)F(RETURN)
strip_end
chars = HOST(2, HOST(3)) ;* Get command line argument
chars = IDENT(chars) "aei"
again line = INPUT :F(END)
OUTPUT = strip(line, chars) :(again)
END
- Output:
snobol4 strip.sno aei She was a soul stripper. She took my heart. Sh ws soul strppr. Sh took my hrt.
Standard ML
fun stripchars (string, chars) = let
fun aux c =
if String.isSubstring (str c) chars then
""
else
str c
in
String.translate aux string
end
- Testing:
- stripchars ("She was a soul stripper. She took my heart!", "aei") ; val it = "Sh ws soul strppr. Sh took my hrt!" : string
Alternately:
fun stripchars (string, chars) =
String.concat (String.tokens (fn c => String.isSubstring (str c) chars) string)
- Testing:
- stripchars ("She was a soul stripper. She took my heart!", "aei") ; val it = "Sh ws soul strppr. Sh took my hrt!" : string
Stringle
a "She was a soul stripper. She took my heart!"
b "aei"
#a
c c .a
b %.\c #c #:c
a :a
#a
$ c
- Output:
Sh ws soul strppr. Sh took my hrt!
Swift
extension String {
func stripCharactersInSet(chars: [Character]) -> String {
return String(seq: filter(self) {find(chars, $0) == nil})
}
}
let aString = "She was a soul stripper. She took my heart!"
let chars: [Character] = ["a", "e", "i"]
println(aString.stripCharactersInSet(chars))
- Output:
Sh ws soul strppr. Sh took my hrt!
Tcl
proc stripchars {str chars} {
foreach c [split $chars ""] {set str [string map [list $c ""] $str]}
return $str
}
set s "She was a soul stripper. She took my heart!"
puts [stripchars $s "aei"]
TorqueScript
This uses a default function.
$string = "She was a soul stripper. She took my heart!"; $chars = "aei"; $newString = stripChars($string, $chars); echo($string); echo($newString);
Output:
She was a soul stripper. She took my heart! Sh ws soul strppr. Sh took my hrt!
Transd
#lang transd
MainModule: {
_start: (λ
(with s "She was a soul stripper. She took my heart!"
(textout (replace s "(a|e|i)" "")))
)
}
- Output:
Sh ws soul strppr. Sh took my hrt!
True BASIC
FUNCTION stripchars$(text$, remove$)
LET s$ = text$
FOR i = 1 TO LEN(remove$)
DO
LET t = POS(s$, (remove$)[i:i])
IF t <> 0 THEN LET s$ = (s$)[1:t-1] & (s$)[t+1:maxnum] ELSE EXIT DO
LOOP
NEXT i
LET stripchars$ = s$
END FUNCTION
PRINT stripchars$("She was a soul stripper. She took my heart!", "aei")
END
TUSCRIPT
$$ MODE TUSCRIPT,{}
string="She was a soul stripper. She took my heart!"
stringstrip=EXCHANGE (string,"_[aei]__")
print string
print stringstrip
Output:
She was a soul stripper. She took my heart! Sh ws soul strppr. Sh took my hrt!
TXR
This solution builds up a regular expression in a hygienic way from the set of characters given as a string.
The string is broken into a list, which is used to construct a regex abstract syntax tree for a character set match, using a Lisp quasiquote. This is fed to the regex compiler, which produces an executable machine that is then used with regsub
.
On the practical side, some basic structural pattern matching is used to process command line argument list.
Since the partial argument list (the arguments belonging to the TXR script) is a suffix of the full argument list (the complete arguments which include the invoking command and the script name), the classic Lisp function ldiff
comes in handy in obtaining just the prefix, for printing the usage:
(defun strip-chars (str set)
(let* ((regex-ast ^(set ,*(list-str set)))
(regex-obj (regex-compile regex-ast)))
(regsub regex-obj "" str)))
(defun usage ()
(pprinl `usage: @{(ldiff *full-args* *args*) " "} <string> <set>`)
(exit 1))
(tree-case *args*
((str set extra) (usage))
((str set . junk) (pprinl (strip-chars str set)))
(else (usage)))
- Output:
$ txr strip-chars-2.tl usage: txr strip-chars-2.tl <string> <set> $ txr strip-chars-2.tl "she was a soul stripper. she stole my heart." "aei" sh ws soul strppr. sh stol my hrt.
Now here is a rewrite of strip-chars
which just uses classic Lisp that has been generalized to work over strings, plus the do
syntax (a sibling of the op
operator) that provides syntactic sugar for a lambda function whose body is an operator or macro form.
(defun strip-chars (str set)
(mappend (do if (memq @1 set) (list @1)) str))
(do if (memq @1 set) (list @1))
is just (lambda (item) (if (memq item set) (list item)))
.
mappend
happily maps over strings and since the leftmost input sequence is a string, and the return values of the lambda are sequence of characters, mappend
produces a string.
UNIX Shell
One would normally do this using the standard tr(1) command:
strip_chars() {
echo "$1" | tr -d "$2"
}
But it can also be accomplished with bash's built-in parameter expansions:
function strip_chars {
echo "${1//[$2]}"
}
Test code:
strip_chars "She was a soul stripper. She took my heart!" aei
- Output:
Sh ws soul strppr. Sh took my hrt!
Ursala
Normally there's no need to define this operation because it's built in.
strip = ~&j
#cast %s
test = strip('she was a soul stripper. she took my heart','aei')
- Output:
'sh ws soul strppr. sh took my hrt'
VBA
Pass the optional bSpace parameter True to replace stripped characters with spaces, otherwise replaced with null.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)
Dim i As Integer, stReplace As String
If bSpace = True Then
stReplace = " "
Else
stReplace = ""
End If
For i = 1 To Len(stStripChars)
stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)
Next i
StripChars = stString
End Function
- Output:
' with bSpace = True: Sh w s soul str pp r. Sh took my h rt! 'with bSpace = False / omitted: Sh ws soul strppr. Sh took my hrt!
VBScript
Function stripchars(s1,s2)
For i = 1 To Len(s1)
If InStr(s2,Mid(s1,i,1)) Then
s1 = Replace(s1,Mid(s1,i,1),"")
End If
Next
stripchars = s1
End Function
WScript.StdOut.Write stripchars("She was a soul stripper. She took my heart!","aei")
- Output:
Sh ws soul strppr. Sh took my hrt!
V (Vlang)
fn main() {
println(stripchars("She was a soul stripper. She took my heart!","aei"))
}
fn stripchars(str string, charstrip string) string {
mut newstr := str
for element in charstrip {newstr = newstr.replace(element.ascii_str(), '')}
return newstr
}
- Output:
Sh ws soul strppr. Sh took my hrt!
Wren
var stripChars = Fn.new { |s, t|
return s.map { |c|
return (t.indexOf(c) == -1) ? c : ""
}.join()
}
System.print(stripChars.call("She was a soul stripper. She took my heart!", "aei"))
- Output:
Sh ws soul strppr. Sh took my hrt!
XPL0
string 0; \make strings zero-terminated
func In(Char, Chars); \Is Char in the string Chars?
char Char, Chars;
int I;
for I:= 0 to -1>>1 do \for many times...
[if Chars(I) = 0 then return false;
if Chars(I) = Char then return true;
];
func StripChars(String, Chars); \Remove Chars from String
char String, Chars;
int I, O;
[O:= 0;
for I:= 0 to -1>>1 do \for many times...
[if not In(String(I), Chars) then
[String(O):= String(I); O:= O+1];
if String(I)=0 then return String;
];
];
Text(0, StripChars("She was a soul stripper. She took my heart!", "aei"))
Output:
Sh ws soul strppr. Sh took my hrt!
Yabasic
sub stripchars$(text$, remove$)
local i, t, s$
s$ = text$
for i = 1 to len(remove$)
do
t = instr(s$, mid$(remove$, i, 1))
if t then s$ = left$(s$, t - 1) + mid$(s$, t + 1) else break : fi
loop
next i
return s$
end sub
print stripchars$("She was a soul stripper. She took my heart!", "aei")
zkl
println("She was a soul stripper. She took my heart!" - "aei")
//-->Sh ws soul strppr. Sh took my hrt!
- Programming Tasks
- String manipulation
- Strings
- 11l
- 360 Assembly
- 8080 Assembly
- 8086 Assembly
- ABC
- Action!
- Ada
- Aime
- ALGOL 68
- ALGOL W
- Amazing Hopper
- APL
- AppleScript
- Applesoft BASIC
- Arturo
- Asymptote
- AutoHotkey
- AWK
- BaCon
- BASIC
- Chipmunk Basic
- IS-BASIC
- Sinclair ZX81 BASIC
- BASIC256
- BBC BASIC
- BCPL
- BQN
- Bracmat
- Burlesque
- C
- Gadget
- C sharp
- C++
- Clojure
- CLU
- COBOL
- ColdFusion
- Common Lisp
- D
- Delphi
- Draco
- EasyLang
- EchoLisp
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- Excel
- F Sharp
- Factor
- Forth
- Fortran
- FreeBASIC
- Frink
- Fōrmulæ
- FutureBasic
- Gambas
- Go
- Groovy
- Haskell
- Icon
- Unicon
- Insitux
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Kotlin
- Lambdatalk
- Lasso
- Liberty BASIC
- LiveCode
- Logo
- Lua
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Nanoquery
- Nemerle
- NetRexx
- NewLISP
- Nim
- Objective-C
- OCaml
- Oforth
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- PHP
- Picat
- PicoLisp
- PL/I
- PL/M
- Powershell
- Prolog
- PureBasic
- Python
- Quackery
- Racket
- Raku
- Red
- Refal
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- SAS
- S-BASIC
- Scala
- Scheme
- ScriptBasic
- Sed
- Seed7
- SETL
- Sidef
- Slope
- Smalltalk
- SNOBOL4
- Standard ML
- Stringle
- Swift
- Tcl
- TorqueScript
- Transd
- True BASIC
- TUSCRIPT
- TXR
- UNIX Shell
- Ursala
- Bc/Omit
- Openscad/Omit
- VBA
- VBScript
- V (Vlang)
- Wren
- XPL0
- Yabasic
- Zkl
- Pages with too many expensive parser function calls