Strip a set of characters from a string: Difference between revisions
Strip a set of characters from a string (view source)
Revision as of 16:27, 5 April 2024
, 2 months ago→{{header|Kotlin}}: Corrected Kotlin solution: the use of regex is error-prone, e.g. `stripChars("fails to remove ] bracket", "aei]")`
(→{{header|Kotlin}}: Corrected Kotlin solution: the use of regex is error-prone, e.g. `stripChars("fails to remove ] bracket", "aei]")`) |
|||
(88 intermediate revisions by 53 users not shown) | |||
Line 1:
{{task|String manipulation}}
[[Category:Strings]]
;Task:
Line 11 ⟶ 12:
<br>
The returned string should contain the first string, stripped of any characters in the second argument:
<
Sh ws soul strppr. Sh took my hrt!</
{{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.
<
STRIPCH CSECT
USING STRIPCH,R13 base register
Line 91 ⟶ 108:
* ---- -------------------------------------------------------
YREGS
END STRIPCH</
{{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}}==
<
procedure Strip_Characters_From_String is
Line 124 ⟶ 294:
begin -- main
Ada.Text_IO.Put_Line(Strip(S, "aei"));
end Strip_Characters_From_String;</
{{out}}
<pre>> ./strip_characters_from_string
Line 130 ⟶ 300:
=={{header|Aime}}==
<
stripchars1(
{
integer p;
}
}
text
stripchars2(
{
}
Line 167 ⟶ 330:
return 0;
}</
=={{header|ALGOL 68}}==
Line 173 ⟶ 336:
{{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''.}}
<
PROC strip chars = (STRING mine, ore)STRING: (
Line 185 ⟶ 348:
);
printf(($gl$,stripchars("She was a soul stripper. She took my heart!","aei")))</
{{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}}==
Line 195 ⟶ 451:
{{works with|AppleScript|Mac OS X 10.6}}
<
on stripChar(str, chrs)
Line 207 ⟶ 463:
end tell
return str
end stripChar</
{{out}}
<pre>
Line 218 ⟶ 474:
(Following the Haskell contribution in reversing the argument order to the sequence more probable in a context of potential currying or partial application).
<
on stripChars(
script notNeedles
on |λ|(x)
end |λ|
end script
intercalate("", filter(notNeedles,
end stripChars
on run
Line 239 ⟶ 495:
-- filter :: (a -> Bool) -> [a] -> [a]
Line 254 ⟶ 510:
end filter
-- intercalate :: Text -> [Text] -> Text
Line 266 ⟶ 518:
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
Line 277 ⟶ 530:
end script
end if
end mReturn</
{{Out}}
<pre>"Sh ws soul strppr. Sh took my hrt!"</pre>
Line 284 ⟶ 537:
OS X Yosemite onwards – importing the Foundation classes to use NSRegularExpression
<
--------- STRIP A SET OF CHARACTERS FROM A STRING --------
-- stripChars :: String -> String -> String
on stripChars(
intercalate("",
splitRegex("[" & needles & "]", haystack))
end stripChars
on run
Line 304 ⟶ 561:
-- splitRegex :: RegexPattern -> String -> [String]
Line 336 ⟶ 593:
end if
end splitRegex
-- regexMatches :: RegexPattern -> String -> [{location:Int, length:Int}]
Line 352 ⟶ 610:
lstMatches
end regexMatches
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 364 ⟶ 623:
end tell
end foldl
-- intercalate :: Text -> [Text] -> Text
Line 372 ⟶ 632:
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
Line 383 ⟶ 644:
end script
end if
end mReturn</
{{Out}}
<pre>"Sh ws soul strppr. Sh took my hrt!"</pre>
=={{header|Applesoft BASIC}}==
<
110 LET RM$ = "AEI"
120 GOSUB 200STRIPCHARS
Line 408 ⟶ 669:
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}}==
<
StripChars(string, charsToStrip){
Line 419 ⟶ 699:
StringReplace, string, string, % A_LoopField, , All
return string
}</
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
=={{header|AWK}}==
<
BEGIN {
x = "She was a soul stripper. She took my heart!";
Line 430 ⟶ 710:
gsub(/[aei]/,"",x);
print x;
}</
{{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!
Line 438 ⟶ 728:
=={{header|BASIC}}==
{{works with|QBasic}}
<
PRINT stripchars$("She was a soul stripper. She took my heart!", "aei")
Line 456 ⟶ 746:
NEXT
stripchars$ = s
END FUNCTION</
{{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.
<
20 LET B$="AEI"
30 GOSUB 60
Line 475 ⟶ 803:
120 LET C$=C$+A$(I)
130 NEXT I
140 RETURN</
{{out}}
<pre>SH WS SOUL STRPPR. SH TOOK MY HRT.</pre>
Line 481 ⟶ 809:
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}}==
<
END
Line 495 ⟶ 835:
UNTIL C% = 0
NEXT
= A$</
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.
<
= string chars s pat
. !arg:(?string.?chars)
Line 525 ⟶ 902:
& out
$ (strip$("Аппетит приходит во время еды".веп)
);</
{{out}}
<pre>Атит риходит о рмя ды</pre>
Line 531 ⟶ 908:
=={{header|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}}==
<
#include <stdio.h>
#include <stdlib.h>
Line 565 ⟶ 942:
free(new);
return 0;
}</
{{out|Result}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
===With table lookup===
<
#include <stdlib.h>
#include <string.h>
Line 607 ⟶ 984:
return 0;
}</
==={{header|
<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";
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}}==
<
public static string RemoveCharactersFromString(string testString, string removeChars)
Line 651 ⟶ 1,030:
}
return returnString;
}</
Usage:
<
using System;
Line 665 ⟶ 1,044:
}
}
</syntaxhighlight>
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
Using <code>Regex</code>:
<
using System;
using System.Text.RegularExpressions;
Line 677 ⟶ 1,056:
string pattern = "[" + removeChars + "]";
return Regex.Replace(testString, pattern, "");
}</
<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}}==
<
(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!"</
=={{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).
<
PROGRAM-ID. Strip-Chars.
Line 734 ⟶ 1,188:
GOBACK
.</
=={{header|ColdFusion}}==
<
<Cfset theString = 'She was a soul stripper. She took my heart!'>
<Cfset theStrip = 'aei'>
Line 744 ⟶ 1,198:
</Cfloop>
<Cfoutput>#theString#</Cfoutput>
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(remove-if (lambda (ch) (find ch chars)) str))
Line 759 ⟶ 1,213:
" A string ")
;; => "A string"
</syntaxhighlight>
=={{header|D}}==
This example shows both the functional and regex solutions.
<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() {
string chars = "aei";
writeln(stripchars(s, chars));
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}}==
<
{$APPTYPE CONSOLE}
Line 791 ⟶ 1,263:
Writeln(TEST_STRING);
Writeln(StripChars(TEST_STRING, 'aei'));
end.</
=={{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}}==
<
;; using regexp /[chars]/g
Line 802 ⟶ 1,318:
(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>
Line 822 ⟶ 1,340:
=={{header|Elixir}}==
The easiest solution would be to use replace from the String module, which takes a Regex.
<
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:
<
def stripchars(str, chars) do
String.replace(str, ~r/[#{chars}]/, "")
Line 835 ⟶ 1,353:
str = "She was a soul stripper. She took my heart!"
RC.stripchars(str, "aei")
# => Sh ws soul strppr. Sh took my hrt!</
=={{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}}==
Line 855 ⟶ 1,389:
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.
<
include std\console.e
Line 862 ⟶ 1,396:
originalString = transmute(originalString, {{} , "a", "e", "i"}, {{} , "", "", ""})
puts(1,"After : " & originalString & "\n")
any_key()</
{{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
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}}==
Line 886 ⟶ 1,492:
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
<
: strippers ( -- addr len) s" aeiAEI" ; \ a string literal returns addr and length
Line 901 ⟶ 1,507:
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
Line 908 ⟶ 1,514:
===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 ;
Line 914 ⟶ 1,522:
: "aei" s" aei" ;
\ usage: "aei" s" She was a soul stripper. She took my heart!" stripchars</
=={{header|Fortran}}==
<
character(len=*), intent(inout) :: string
character(len=*), intent(in) :: set
Line 933 ⟶ 1,541:
end if
end do
end subroutine strip</
=={{header|FreeBASIC}}==
<
Function stripChars(s As Const String, chars As Const String) As String
Line 968 ⟶ 1,576:
Print
Print "Press any key to quit"
Sleep</
{{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>
Line 977 ⟶ 1,634:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=f199a8f7a56cf466e4a16c3fc71f6278 Click this link to run this code]'''
<
Print StripChars("She was a soul stripper. She took my heart!", "aei")
Line 992 ⟶ 1,649:
Return sText
End</
Output:
<pre>
Line 999 ⟶ 1,656:
=={{header|Go}}==
<
import (
Line 1,018 ⟶ 1,675:
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}</
{{out}}
<pre>
Line 1,026 ⟶ 1,683:
=={{header|Groovy}}==
Solution:
<
def list = string as List
list.removeAll(stripChars as List)
list.join()
}</
Test:
<
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
Line 1,038 ⟶ 1,695:
=={{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.
<
stripChars = filter . flip notElem</
{{out|Testing in GHCI}}
<pre>> stripChars "aei" "She was a soul stripper. She took my heart!"
Line 1,046 ⟶ 1,703:
=={{header|Icon}} and {{header|Unicon}}==
The following works in both languages:
<
cs := \A[1] | 'aei' # argument is set of characters to strip
every write(stripChars(!&input, cs)) # strip all input lines
Line 1,055 ⟶ 1,712:
s ? while ns ||:= (not pos(0), tab(upto(cs)|0)) do tab(many(cs))
return ns
end</
{{out|Sample runs}}
<pre>->strip
Line 1,066 ⟶ 1,723:
rdvrks r nt trs.
-></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}}==
Line 1,071 ⟶ 1,736:
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}}
<
Sh ws soul strppr. Sh took my hrt!</
=={{header|Java}}==
The most basic approach is to use the ''String.replace'' method.
<syntaxhighlight lang="java">
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|JavaScript}}==
Line 1,097 ⟶ 1,778:
===ES5===
<
return string.replace(RegExp('['+chars+']','g'), '');
}</
===ES6===
Line 1,105 ⟶ 1,786:
Reversing the order of the arguments, to simplify any currying:
<
'use strict';
Line 1,125 ⟶ 1,806:
// 'Sh ws soul strppr. Sh took my hrt!'
})();</
{{Out}}
Line 1,132 ⟶ 1,813:
Alternatively, we could also do this without a regex:
<
'use strict';
Line 1,158 ⟶ 1,839:
// 'Sh ws soul strppr. Sh took my hrt!'
})();</
{{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}}==
<
(string | explode) - (banish | explode) | implode;</
'''Note''': In jq, it would be more idiomatic to define the function as a filter:
<
explode - (banish | explode) | implode;</
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"))
}</
{{out}}
Line 1,203 ⟶ 1,885:
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}}==
<
with toremove in #destroy->values do => {
#in->replace(#toremove,'')
Line 1,211 ⟶ 1,918:
return #in
}
stripper('She was a soul stripper. She took my heart!','aei')</
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
=={{header|Liberty BASIC}}==
<
End
Line 1,251 ⟶ 1,934:
Next i
If (num <= Len(chars$)) Then stripchars$ = stripchars$(stripchars$, chars$, (num + 1))
End Function</
=={{header|LiveCode}}==
<
local strstripped
put str into strstripped
Line 1,262 ⟶ 1,944:
end repeat
return strstripped
end stripChars</
Test<
put stripchars("She was a soul stripper. She took my heart!","aei")
end teststripchars</
=={{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}}==
<
Remove(c->Has("aei",c), "She was a soul stripper. She took my heart!");</
Output:
<pre> "Sh ws soul strppr. Sh took my hrt!"</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
stripchars["She was a soul stripper. She took my heart!","aei"]
->Sh ws soul strppr. Sh took my hrt!</
=={{header|MATLAB}} / {{header|Octave}}==
<
% MATLAB after 2016b: str = erase(str, charlist);
str(ismember(str, charlist)) = '';</
{{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}}==
<
{
def chuck = Explode(remove);
Concat( "", Split(text, chuck))
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols
Line 1,310 ⟶ 2,024:
end c_
return haystack</
=={{header|NewLISP}}==
<
(replace "[aei]" sentence "" 0))</
=={{header|Nim}}==
<
echo "She was a soul stripper. She took my heart!".split({'a','e','i'}).join()
echo
("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>
Line 1,333 ⟶ 2,054:
{{works with|Mac OS X|10.5+}}
{{works with|iOS|1.0}}
<
- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars;
@end
Line 1,341 ⟶ 2,062:
return [[self componentsSeparatedByCharactersInSet:chars] componentsJoinedByString:@""];
}
@end</
{{out|To use}}
<
NSCharacterSet* chars = [NSCharacterSet characterSetWithCharactersInString:@"aei"];
// Display the NSString.
NSLog(@"%@", [aString stripCharactersInSet:chars]);</
=={{header|OCaml}}==
<
let len = String.length s in
let res =
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
aux (succ i) (succ j)
end
in
aux 0 0</
{{out|Testing in the toplevel}}
<pre># stripchars "She was a soul stripper. She took my heart!" "aei" ;;
- : string = "Sh ws soul strppr. Sh took my hrt!"</pre>
=={{header|Oforth}}==
<
"She was a soul stripper. She took my heart!" stripChars("aei") println</
{{out}}
Line 1,381 ⟶ 2,102:
=={{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>...
<
bad=Set(Vec(Vecsmall(bad)));
s=Vecsmall(s);
Line 1,388 ⟶ 2,109:
Strchr(v)
};
stripchars("She was a soul stripper. She took my heart!","aei")</
=={{header|Pascal}}==
Line 1,395 ⟶ 2,116:
=={{header|Perl}}==
Note: this example uses a regular expression character class. Certain characters, like hyphens and brackets, may need to be escaped.
<
my ($s, $chars) = @_;
$s =~ s/[$chars]//g;
Line 1,401 ⟶ 2,122:
}
print stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";</
{{out}}
<pre>
Line 1,407 ⟶ 2,128:
</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.
<
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:
<
my ($s, $chars) = @_;
eval("\$s =~ tr/$chars//d;");
return $s;
}</
=={{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>
Line 1,439 ⟶ 2,147:
=={{header|PHP}}==
<
function stripchars($s, $chars) {
return str_replace(str_split($chars), "", $s);
Line 1,445 ⟶ 2,153:
echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
?></
{{out}}
<pre>
Sh ws soul strppr. Sh took my hrt!
</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}}==
<
(pack (diff (chop Str1) (chop Str2))) )</
{{out}}
<pre>: (strDiff "She was a soul stripper. She took my heart!" "aei")
Line 1,459 ⟶ 2,195:
=={{header|PL/I}}==
<
declare text character (*) varying, chars character (*) varying;
declare out_text character (100);
Line 1,472 ⟶ 2,208:
end;
return (substr(out_text, 1, j) );
end strip_chars;</
=={{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:
<
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 .
<
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}}==
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.
<
Protected i, *ptrChar.Character, length = Len(source), result.s
*ptrChar = @source
Line 1,514 ⟶ 2,330:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
Line 1,521 ⟶ 2,337:
===Not using regular expressions===
{{works with|Python|2.6+}}
<
... return s.translate(None, chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'</
{{works with|Python|2.x}}
<
>>> 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:
<
... 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===
<
>>> def stripchars(s, chars):
return re.sub('[%s]+' % re.escape(chars), '', s)
Line 1,546 ⟶ 2,362:
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
>>> </
=={{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
Line 1,561 ⟶ 2,402:
(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"</
=={{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).
<
say stripChars('She was a soul stripper. She took my heart!', "iea") /*elide: iea */
exit /*stick a fork in it, we're all done. */
Line 1,579 ⟶ 2,443:
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]].
<br><br>
Line 1,589 ⟶ 2,453:
===version 2===
Using recursion:
<syntaxhighlight lang="rexx">/* REXX */
say StripChars('She was a soul stripper. She took my heart!','iea')
exit 0
Line 1,599 ⟶ 2,462:
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.)
<
/* REXX ***************************************************************
* If source and stripchars don't contain a hex 00 character, this works
Line 1,621 ⟶ 2,484:
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
<
stripchars: Procedure
Parse Arg i,s /* get input and chars to be removed */
Line 1,636 ⟶ 2,499:
End
Return o /* return the result */
</syntaxhighlight>
=={{header|Ring}}==
<
aList = "She was a soul stripper. She took my heart!"
bList = "aei"
Line 1,650 ⟶ 2,513:
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|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:
<
fn strip_characters(original : &str, to_strip : &str) -> String {
let mut result = String::new();
Line 1,668 ⟶ 2,556:
result
}
</syntaxhighlight>
Functional Implementation:
<
fn strip_characters(original : &str, to_strip : &str) -> String {
original.chars().filter(|&c| !to_strip.contains(c)).collect()
}
</syntaxhighlight>
Either can be executed thusly:
<
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:
<
%let chars=aei;
%let stripped=%sysfunc(compress("&string","&chars"));
%put &stripped;</
Log:
<
=={{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}}==
<
stripChars("She was a soul stripper. She took my heart!", "aei")
// => Sh ws soul strppr. Sh took my hrt!</
=={{header|Scheme}}==
Line 1,705 ⟶ 2,618:
The second uses the SRFI libraries to create a character set and delete those characters from the string.
<
(import (scheme base)
(scheme write)
Line 1,733 ⟶ 2,646:
(display (strip-chars2 "She was a soul stripper. She took my heart!" "aei"))
(newline)
</syntaxhighlight>
{{out}}
Line 1,742 ⟶ 2,655:
=={{header|ScriptBasic}}==
<
str1 = "She was a soul stripper. She took my heart!"
rmv = "aei"
Line 1,749 ⟶ 2,662:
NEXT
PRINT str1,"\n"
</syntaxhighlight>
=={{header|Sed}}==
Using echo and piping it through a sed filter:
<
strip_char()
{
echo "$1" | sed "s/[$2]//g"
}</
=={{header|Seed7}}==
<
const func string: stripchars (in string: mainStri, in string: charList) is func
Line 1,778 ⟶ 2,691:
begin
writeln(stripchars("She was a soul stripper. She took my heart!", "aei"));
end func;</
{{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}}==
<
str.tr(char_list, "", "d");
}</
or:
<
str.chars.grep {|c| !char_list.contains(c)}.join;
}</
Calling the function:
<
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
=={{header|
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)))))
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
=={{header|Smalltalk}}==
{{works with|Pharo|1.3-13315}}
<
stripChars := [ :string :chars |
string reject: [ :c | chars includes: c ] ].
Line 1,828 ⟶ 2,751:
value: 'aei'.
"'Sh ws soul strppr. Sh took my hrt!'"</
=={{header|SNOBOL4}}==
Note: "strip" is a function, its argument, the label of its first executed line, and its returned value.
<
strip strip ANY(c) = :S(strip)F(RETURN)
strip_end
Line 1,841 ⟶ 2,764:
again line = INPUT :F(END)
OUTPUT = strip(line, chars) :(again)
END</
{{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}}==
<
func stripCharactersInSet(chars: [Character]) -> String {
return String(seq: filter(self) {find(chars, $0) == nil})
Line 1,857 ⟶ 2,813:
let chars: [Character] = ["a", "e", "i"]
println(aString.stripCharactersInSet(chars))</
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
=={{header|Tcl}}==
<
foreach c [split $chars ""] {set str [string map [list $c ""] $str]}
return $str
Line 1,868 ⟶ 2,824:
set s "She was a soul stripper. She took my heart!"
puts [stripchars $s "aei"]</
=={{header|TorqueScript}}==
Line 1,882 ⟶ 2,838:
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}}==
<
$$ MODE TUSCRIPT,{}
string="She was a soul stripper. She took my heart!"
Line 1,890 ⟶ 2,875:
print string
print stringstrip
</syntaxhighlight>
Output:
<pre>
Line 1,905 ⟶ 2,890:
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:
<
(let* ((regex-ast ^(set ,*(list-str set)))
(regex-obj (regex-compile regex-ast)))
Line 1,917 ⟶ 2,902:
((str set extra) (usage))
((str set . junk) (pprinl (strip-chars str set)))
(else (usage)))</
{{out}}
<pre>$ txr strip-chars-2.tl
Line 1,926 ⟶ 2,911:
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.
<
(mappend (do if (memq @1 set) (list @1)) str))</
<code>(do if (memq @1 set) (list @1))</code> is just <code>(lambda (item) (if (memq item set) (list item)))</code>.
Line 1,935 ⟶ 2,920:
One would normally do this using the standard tr(1) command:
{{works with|sh}}
<
echo "$1" | tr -d "$2"
}</
But it can also be accomplished with bash's built-in parameter expansions:
{{works with|bash}}
<
echo "${1//[$2]}"
}</
Test code:
<
{{out}}
<pre>Sh ws soul strppr. Sh took my hrt!</pre>
Line 1,950 ⟶ 2,935:
=={{header|Ursala}}==
Normally there's no need to define this operation because it's built in.
<
#cast %s
test = strip('she was a soul stripper. she took my heart','aei')</
{{out}}
<pre>
Line 1,962 ⟶ 2,947:
{{omit from|Bc}}
{{omit from|Openscad}}
=={{header|VBA}}==
Pass the optional bSpace parameter True to replace stripped characters with spaces, otherwise replaced with null.
<
Dim i As Integer, stReplace As String
If bSpace = True Then
Line 1,978 ⟶ 2,962:
Next i
StripChars = stString
End Function</
{{out}}
Line 1,988 ⟶ 2,972:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function stripchars(s1,s2)
For i = 1 To Len(s1)
Line 1,999 ⟶ 2,983:
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}}==
<
//-->Sh ws soul strppr. Sh took my hrt!</
|