Strip a set of characters from a string

From Rosetta Code
Jump to: navigation, search
Task
Strip a set of characters from a string
You are encouraged to solve this task according to the task description, using any language you may know.

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:

 print stripchars("She was a soul stripper. She took my heart!","aei")
Sh ws soul strppr. Sh took my hrt!

Contents

[edit] 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!

[edit] Aime

text
stripchars(text s, text w)
{
integer p;
data b;
 
b_cast(b, s);
p = b_look(b, 0, w);
while (p < b_length(b)) {
b_delete(b, p);
p += b_look(b, p, w);
}
 
return b_string(b);
}
 
integer
main(void)
{
o_text(stripchars("She was a soul stripper. She took my heart!", "aei"));
o_newline();
 
return 0;
}
Output:
Sh ws  soul strppr. Sh took my hrt!

[edit] ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.
#!/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!

[edit] 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!

[edit] 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!

[edit] 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!

[edit] BASIC

Works with: 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
Output:
Sh ws  soul strppr. Sh took my hrt!

See also: Liberty BASIC, PureBasic

[edit] 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!

[edit] 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:
Атит риходит о рмя ды

[edit] Burlesque

 
blsq ) "She was a soul stripper. She took my heart!"{"aei"\/~[n!}f[
"Sh ws soul strppr. Sh took my hrt!"
 

[edit] 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!

[edit] 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.

[edit] C++

Works with: C++11
#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!

[edit] 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, "");
}

[edit] 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!"

[edit] 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
.

[edit] 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>
 

[edit] 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!"

[edit] D

import std.stdio, std.string;
 
void main() {
auto s = "She was a soul stripper. She took my heart!";
auto ss = "Sh ws soul strppr. Sh took my hrt!";
assert(s.removechars("aei") == ss);
}

[edit] 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.

[edit] 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/a|e|i/, "")
# => 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/#{Enum.join(String.split(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!
 

[edit] 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!"

[edit] Euphoria

Works with: Euphoria version 4.0.3, 4.0.0 RC1 and later

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...

[edit] F#

let stripChars text (chars:string) =
Array.fold (
fun (s:string) c -> s.Replace(c.ToString(),"")
) text (chars.ToCharArray())
 
[<EntryPoint>]
let main args =
printfn "%s" (stripChars "She was a soul stripper. She took my heart!" "aei")
0

Output

Sh ws  soul strppr. Sh took my hrt!

[edit] 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.

[edit] 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!

[edit] 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!

[edit] 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!"

[edit] 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.
->

[edit] 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!

[edit] Java

class StripChars {
public static String stripChars(String inString, String toStrip) {
return inString.replaceAll("[" + toStrip + "]", "");
}
 
public static void main(String[] args) {
String sentence = "She was a soul stripper. She took my heart!";
String chars = "aei";
System.out.println("sentence: " + sentence);
System.out.println("to strip: " + chars);
System.out.println("stripped: " + stripChars(sentence, chars));
}
}
Output:
sentence: She was a soul stripper. She took my heart!
to strip: aei
stripped: Sh ws  soul strppr. Sh took my hrt!

[edit] JavaScript

function stripchars(string, chars) {
return string.replace(RegExp('['+chars+']','g'), '');
}


[edit] 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!

[edit]

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!

[edit] Lua

 
function stripchars(str, chrs)
local s = str:gsub("["..chrs.."]", '')
return s
end
 
print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) )
 

[edit] 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


[edit] 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!"

[edit] 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!

[edit] MATLAB / Octave

  function str = stripchars(str, charlist)
charlist = unique(charlist);
for k=1:length(charlist)
str(str==charlist(k)) = [];
end;
end;
Output:
 >>stripchars('She was a soul stripper. She took my heart!','aei')
ans = Sh ws  soul strppr. Sh took my hrt!

[edit] Nemerle

StripChars( text : string, remove : string ) : string
{
def chuck = Explode(remove);
Concat( "", Split(text, chuck))
}

[edit] 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

[edit] Nimrod

import strutils
 
proc `$` (x: seq[string]): string =
result = x.join("")
 
echo(split("She was a soul stripper. She took my heart!", {'a','e','i'}).join(""))
 
# using the above proc to overload the toString operator `$` as an alternative to using join()
echo($split("She was a soul stripper. She took my heart!", {'a','e','i'}))
Output:
Sh ws  soul strppr. Sh took my hrt!
Sh ws  soul strppr. Sh took my hrt!

[edit] Objective-C

Works with: Mac OS X version 10.5+
Works with: iOS version 1.0
@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]);

[edit] OCaml

let stripchars s cs =
let len = String.length s in
let res = String.create len in
let rec aux i j =
if i >= len then String.sub res 0 j
else if String.contains cs s.[i] then
aux (succ i) (j)
else begin
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!"

[edit] 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")

[edit] Pascal

See Delphi

[edit] 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;
}

[edit] 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!

[edit] 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!

[edit] 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!"

[edit] 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;

[edit] 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!".

[edit] 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!

[edit] Python

[edit] Not using regular expressions

Works with: Python version 2.6+
>>> 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!'
Works with: Python version 2.x
>>> 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!'

[edit] 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!'
>>>

[edit] 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 ""))
 

[edit] REXX

[edit] version 1

In the REXX language, strip usually means to remove leading and/or trailing characters from a string (most often, blanks).

/*REXX program to remove a set of characters from a string  (haystack). */
say stripChars('She was a soul stripper. She took my heart!', "iea")
exit /*stick a fork in it, we're done.*/
/*───────────────────────────────────STRIPCHARS subroutine──────────────*/
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!

[edit] 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 */
 

[edit] 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 */
 

[edit] Ruby

>> "She was a soul stripper. She took my heart!".delete("aei")
=> "Sh ws soul strppr. Sh took my hrt!"

[edit] 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!

[edit] 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!

[edit] Sed

Using echo and piping it through a sed filter:

#!/bin/bash
 
strip_char()
{
echo "$1" | sed "s/[$2]//g"
}

[edit] 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!

[edit] 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

[edit] Smalltalk

Works with: Pharo version 1.3-13315
| 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!'"

[edit] 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!


[edit] 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"]

[edit] 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!

[edit] 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!

[edit] 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:


@(do
(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.txr 
usage: txr strip-chars-2.txr <string> <set>
$ txr strip-chars-2.txr "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.

[edit] UNIX Shell

One would normally do this using the standard tr(1) command:

Works with: sh
strip_chars() {
echo "$1" | tr -d "$2"
}

But it can also be accomplished with bash's built-in parameter expansions:

Works with: bash
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!

[edit] 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'


[edit] 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!

[edit] zkl

println("She was a soul stripper. She took my heart!"-"aei")
//-->Sh ws soul strppr. Sh took my hrt!
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox