Strip control codes and extended characters from a string: Difference between revisions

m
(→‎{{header|Haskell}}: Reduced the expression in terms of a liftA2 composition over two other functions.)
m (→‎{{header|Wren}}: Minor tidy)
 
(43 intermediate revisions by 23 users not shown)
Line 1:
{{task}}
The task is to strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:
 
;Task:
* a string with control codes stripped (but extended characters not stripped)
* a string withStrip control codes and extended characters strippedfrom a string.
 
 
The solution should demonstrate how to achieve each of the following results:
In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.
:*   a string with control codes stripped (but extended characters not stripped)
:*   a string with control codes and extended characters stripped
 
 
In ASCII, the control codes have decimal codes 0 through to 31 and 127.
 
On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.
 
On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F stripped(s)
R s.filter(i -> Int(i.code) C 32..126).join(‘’)
 
print(stripped("\ba\u0000b\n\rc\fd\xc3"))</syntaxhighlight>
 
{{out}}
<pre>
abcd
</pre>
 
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> .model small
.stack 1024
.data
StringStrip db "abc",13,10,8,7,"def",90h
.code
start:
 
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax
mov ax,03h
int 10h ;clear screen
mov si,offset StringStrip
call PrintString_PartiallyStripped
call NewLine
mov si,offset StringStrip
call PrintString_Stripped
 
mov ax,4C00h
int 21h ;return to DOS
PrintString_Stripped:
;prints a null-terminated string
;all other control codes are stripped.
lodsb
cmp al,0
jz Terminated
;not equal to zero
cmp al,21h ; if (AL < 21h)
jb PrintString_Stripped ;skip this character and keep going
cmp al,7Fh ; if (AL >= 7Fh)
jae PrintString_Stripped ;skip this character and keep going
mov ah,02h
mov dl,al
int 21h ;prints character in DL to screen
jmp PrintString_Stripped
Terminated:
ret
PrintString_PartiallyStripped:
;strips control codes but not extended ascii.
;The null terminator isn't stripped of course.
lodsb
cmp al,0
jz Terminated_PartiallyStripped
cmp al,21h
jb PrintString_PartiallyStripped
cmp al,7Fh
je PrintString_PartiallyStripped ;delete counts as a control code
mov ah,02h
mov dl,al
int 21h
jmp PrintString_PartiallyStripped
Terminated_PartiallyStripped:
ret
 
NewLine:
mov ah,02h
mov dl,13 ;carriage return
int 10h
mov ah,02h
mov dl,10 ;line feed
int 10h
ret
end start</syntaxhighlight>
 
{{out}}
<pre>
abcdefÉ
abcdef
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC IsAscii(CHAR c)
IF c<32 OR c>124 OR c=96 OR c=123 THEN
RETURN (0)
FI
RETURN (1)
 
PROC Strip(CHAR ARRAY src,dst)
CHAR c
BYTE i
 
dst(0)=0
FOR i=1 TO src(0)
DO
c=src(i)
IF IsAscii(c) THEN
dst(0)==+1
dst(dst(0))=c
FI
OD
RETURN
 
PROC Main()
CHAR ARRAY
src(20)=[16 0 16 96 123 'a 'b 'c 131 27 30 '1 '2 '3 4 1 20],
dst(20)
 
PrintF("Original string: ""%S""%E",src)
Strip(src,dst)
PrintF("Stripped string: ""%S""%E",dst)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Strip_control_codes_and_extended_characters_from_a_string.png Screenshot from Atari 8-bit computer]
<pre>
Original string: "♥♣♦♠abc┘←123┤├●"
Stripped string: "abc123"
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Strip_ASCII is
Line 48 ⟶ 187:
Put_Line("Neither_Extended:", Filter(Full, Above => Character'Last)); -- defaults for From and To
end Strip_ASCII;
</syntaxhighlight>
</lang>
 
Output:
Line 58 ⟶ 197:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># remove control characters and optionally extended characters from the string text #
# assums ASCII is the character set #
PROC strip characters = ( STRING text, BOOL strip extended )STRING:
Line 87 ⟶ 226:
STRING t = REPR 2 + "abc" + REPR 10 + REPR 160 + "def~" + REPR 127 + REPR 10 + REPR 150 + REPR 152 + "!";
print( ( "<<" + t + ">> - without control characters: <<" + strip characters( t, FALSE ) + ">>", newline ) );
print( ( "<<" + t + ">> - without control or extended characters: <<" + strip characters( t, TRUE ) + ">>", newline ) )</langsyntaxhighlight>
{{out}}
<pre>
<<�abc
ádef~
ûÿ!>> - without control characters: <<abcádef~ûÿ!>>
<<�abc
ádef~
ûÿ!>> - without control or extended characters: <<abcdef~!>>
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">str: {string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.}
 
print "with extended characters"
print join select split str 'x ->
not? in? to :integer to :char x (0..31)++127
 
print "without extended characters"
print join select split str 'x ->
and? ascii? x
not? in? to :integer to :char x (0..31)++127</syntaxhighlight>
 
{{out}}
 
<pre>with extended characters
string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.
without extended characters
string of , may include control characters and other ilk.</pre>
 
=={{header|AutoHotkey}}==
{{trans|Python}}
<langsyntaxhighlight AHKlang="ahk">Stripped(x){
Loop Parse, x
if Asc(A_LoopField) > 31 and Asc(A_LoopField) < 128
Line 106 ⟶ 264:
return r
}
MsgBox % stripped("`ba" Chr(00) "b`n`rc`fd" Chr(0xc3))</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f STRIP_CONTROL_CODES_AND_EXTENDED_CHARACTERS.AWK
BEGIN {
Line 118 ⟶ 276:
exit(0)
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 125 ⟶ 283:
control and extended stripped: abz (length 3)
</pre>
 
=={{header|BASIC}}==
{{works with|QBasic}}
Line 130 ⟶ 289:
While DOS does support ''some'' extended characters, they aren't entirely standardized, and shouldn't be relied upon.
 
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION strip$ (what AS STRING)
DECLARE FUNCTION strip2$ (what AS STRING)
 
Line 167 ⟶ 326:
NEXT
strip2$ = outP
END FUNCTION</langsyntaxhighlight>
 
Output:
Line 177 ⟶ 336:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> test$ = CHR$(9) + "Fran" + CHR$(231) + "ais." + CHR$(127)
PRINT "Original ISO-8859-1 string: " test$ " (length " ; LEN(test$) ")"
test$ = FNstripcontrol(test$)
Line 203 ⟶ 362:
ENDIF
ENDWHILE
= A$</langsyntaxhighlight>
Output:
<pre>
Line 211 ⟶ 370:
</pre>
 
=={{header|BQN}}==
Using BQN's character arithmetic and comparison, characters are binned using <code>⍋</code> and removed if they are inside the range.
 
<syntaxhighlight lang="bqn">StripCt←((1≠(@+0‿32)⊸⍋)∧(@+127)⊸≠)⊸/
StripCtEx←(1=(@+32‿127)⊸⍋)⊸/</syntaxhighlight>
<syntaxhighlight lang="bqn"> RP←•rand.Deal∘≠⊸⊏ # Random Permutation
(rand).Deal∘≠⊸⊏
ascii←RP @+↕256
s»ã®(Dj×\lÍt'C£rzËèv½`k7YW[¾]ÆF¥*=­ïÝK§0m<Åàý!,JP%Xêÿ}8ñ¶u¿U-TúÞ
·Ä¬âç/ÃøªÎ#VÁ;Û ß6ÐiÜQÈ d
´ò3ÀA©üOØô&.nþ°³ö^c9ºa«2q1NæÖõä ¦
wZóp""Ç+éS¨ "
≠ascii
256
≠StripCt ascii
223
≠StripCtEx ascii
95
unicode←RP @+↕1000
"kȺ=<ɘΙͷƤ̀ÿʅ Ɂ
ϋǒǩƽͱñȤȔ˯BVȱĶțŁ̅Ġ˄ͦ_ǸǦǂɫɒŦˏτȍ5ȒNļʛˁhĹȅǔʣͯĄż̜̍̕Œdz͒ɹĵǖΤÐ)F±-ǿď͚­ƒʵ̈́Ȳ̮ʷːΘ̊ʑĞ©ȗŕƟƹƁˤƩɦΡ̴@ʇ˃ʽ˜UęOīNj1ϐΰŊ¿\ʞ8ʒȧ˾ƭķɡ͠#ǥȀšJŻ͛ȇǷcνĦǑƿƖ!ēö§ɎľêϘK¼ȋȮȕƓ×ȴȝȾȰÕÇ˸͐´ɝ·ȨŐƯ͎ʉΑ$>ʍʬɮΓeÛʋͽʥŨYÖ͇ͮƷ̾͌ƚP£ρŔόɊ̗σŝ͹Ͳʤώɓ͸˙ɀͅǯɤʦιΥÁû̓ž˒ξƢĪ̂̋ͩȫ̥̖͑7ĝÄΕı͆ØQ˘ɐƑ΀ő̼»̇űŚĒ²ĴT,Ȃ¯ϓυúɆɽÈ΂ˮ̏͡Ɛʭ̷˿ãąΧƌħǨŖ̱ɟ/Ǣɸπ π̻
˖áčĈʔŠǪgΦ̑ƇʜƬĢέɲ͖ƈ͙ĚɇȖȩĆǽ̞ˑˬ^ʫϑĂEĜǝɜĨȭɈśœ˽şʲDž͗ηɬ˧ßʮA̪ϧͤΒǭ̈ĿɏŹDŽɗūʌͶ""ίʢɶʂʰˉÆ{Êʟ͓ͬɔŎΉϖθǻƅƛ̯ɃΪ̒ʈ΁ΐ˚ǁ̰΃¶Ȣɼ˶Ĕˢƫϛάɩ̣̄¬˦ʻÓ̙ɕ̘ëƘ̠˝˞ŽʙÑâŶŧϤ̟ªqƱi͂Ÿ˲ΛĖ˭ƾ̶ϟǞƉ̡W:nj͉̆ʚȎ¥ͥήxƗ˫ȟǘʸʡ¢̹u̎mĊˠÂϜͰƥʼnw3ϊ΍ȏϕí˨̲Ƃϣ˺à͜Ο̩ɖ˔%͍ǗƕʺćD͏ơψ½Ôχ˕Ú˴ʹͣΞHȶ˟ϥǹ
ȥ΄LjͿå¸ʗ0ėČlˡ̭DzîȜκŏþγyɚ͢Ǿ˅ʿ̓òŮ«͵ư*̨ϏǧŜ ͈ˇɿͫljğ˱ŞƔƍÎİǠƺς
`ʴ;ƣ̦ȿˋʊƋ̢˩ºůŭè Ȉ}jŤʐƜrɾ˥˓˼Þ[̺˛˳pìʏ́ěRǟɨƴ̝ɣǺʆÍƼÏζȷɛǫǶʧï̽õüȌɌ̳˪ɥƪDZøɄɻĘéņ?Řȳ̚
ȵΖƳɪ̃ł;ǰϦăCňȦ˹tÝċʎ9ϚμńΎεʨðɋ΅aɂįNJ˻Ȫ͕ύĮǮȐǬŅƃĭɉĤ΋ǐͧƮΜvƙƏƻǣĬϢŌˍλƀƦ¡ȠǤ·ȹZôLŵƲ̿α2ſʃµÅĕȞșͭo ř̬ź¹ǛƠŪβȑƶ+ȚȻbŲäƝͪfȘ̀ÀĉϡǙǍ "
≠unicode
1000
≠StripCt unicode
967
≠StripCtEx unicode
95</syntaxhighlight>
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( "string of ☺☻♥♦⌂, may include control
characters and other ilk.\L\D§►↔◄
Rødgrød med fløde"
Line 239 ⟶ 429:
)
)
& );</langsyntaxhighlight>
Output:
<pre>Control characters stripped:
Line 248 ⟶ 438:
 
=={{header|C}}==
 
<lang C>#include <stdio.h>
===<tt>filtered copy and swap</tt>===
 
Take advantage of the the fact that char is an 8-bit integer in C.<br>
Unsigned char is used throughout to enablethe extended ASCII set. <br>
A random function is called to generate a mix of good and bad values.<br>
A temp buffer is created with only valid characters, and swapped for the original.<br>
A true/false function checks if the character is in the valid range.<br>
 
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
#define MAXBUF 256 /* limit */
#define STR_SZ 100 /* string size */
 
 
/* function prototypes */
int ascii (const unsigned char c);
 
int ascii_ext (const unsigned char c);
 
unsigned char* strip(unsigned char* str, const size_t n, int ext );
 
 
/* check a character
return 1 for true
0 for false
*/
int ascii (const unsigned char c)
{
unsigned char min = 32; /* <space> */
unsigned char max = 126; /* ~ tilde */
 
if ( c>=min && c<=max ) return 1;
 
return 0;
}
 
 
/* check if extended character
return 1 for true
0 for false
*/
int ascii_ext (const unsigned char c)
{
unsigned char min_ext = 128;
unsigned char max_ext = 255;
 
if ( c>=min_ext && c<=max_ext )
return 1;
 
return 0;
}
 
 
/* fill buffer with only ASCII valid characters
then rewrite string from buffer
limit to n < MAX chars
*/
 
unsigned char* strip( unsigned char* str, const size_t n, int ext)
{
 
unsigned char buffer[MAXBUF] = {'\0'};
 
size_t i = 0; // source index
size_t j = 0; // dest index
 
size_t max = (n<MAXBUF)? n : MAXBUF -1; // limit size
 
while (i < max )
{
if ( (ext && ascii_ext(str[i]) ) || (ascii(str[i]) ) ) // check
{
buffer[j++] = str[i]; // assign
}
i++;
}
 
memset(str, '\0', max); // wipe string
 
i = 0; // reset count
 
while( i < j)
{
str[i] = buffer[i]; // copy back
i++;
}
 
str[j] = '\0'; // terminate properly
 
return str;
}
 
/* try it out */
int main( int argc, char** argv)
{
enum {ASCII=0, EXT=1}; /* enumeration makes easier reading */
 
unsigned int seed = 134529; // RNG seed value
 
/* variables and storage */
unsigned char badstring[STR_SZ] = {'\0'};
unsigned char bs_2[STR_SZ] = {'\0'};
unsigned char* goodstring = NULL;
unsigned char* goodstring_ext = NULL;
 
size_t i = 0;
 
srand(seed); /* seed RNG */
 
fprintf(stdout, "Original:\t" );
 
/* generate a random string */
for (i = 0; i < STR_SZ; i++)
{
badstring[i] = (unsigned char) ( rand () & (unsigned char)0xFF );
fprintf(stdout, "%c", badstring[i] );
}
fprintf(stdout, "\n");
 
memcpy(bs_2, badstring, STR_SZ * sizeof(unsigned char) ); /* copy string */
 
goodstring_ext = strip( badstring, STR_SZ, EXT); /* remove non-extended and non-ascii */
 
fprintf(stdout, "\nEXT:\t%s\n" , goodstring_ext );
 
goodstring = strip( bs_2, STR_SZ, ASCII); /* remove all non-ascii */
fprintf(stdout, "\nASCII:\t%s\n" , goodstring );
return 0;
}</syntaxhighlight>
 
{{out}}
Original: ƒ˜v�ý8Ç…Ø×�B„…â¤Ê8ln9V¢DèÝz�@ÅTÃ]ÊÙZ� ßÚwo�ûôÿ ¾8 ,qcζK¬0aìõ¶¯R€ˆ­ƒ(Œ]Ÿüz›ðz;¯²GÛ#ªªÙöV z WñQŽyþ�¡
 
EXT: ƒ˜vý8Ç…Ø×�B„…â¤Ê8ln9V¢DèÝz@ÅTÃ]ÊÙZ ßÚwoûôÿ ¾8,qcζK¬0aìõ¶¯R€ˆ­ƒ(Œ]Ÿüz›ðz;¯²GÛ#ªªÙöVWBþñQŽyþ¡</span>
 
ASCII: v8B8ln9VDz@T]Zwo8,qcK0aR(]zz;G#VWBQy
 
 
 
===<tt>apply mask from a table</tt>===
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 311 ⟶ 648:
 
return 0;
}</langsyntaxhighlight>output:<syntaxhighlight lang="text"> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ <odd stuff my xterm thinks are bad unicode hence can't be properly shown>
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~</langsyntaxhighlight>
 
=={{header|C++}}==
<lang Cpp>#include <string>
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/casts.hpp>
#include <ctime>
#include <cstdlib>
using namespace boost::lambda ;
 
struct MyRandomizer {
char operator( )( ) {
return static_cast<char>( rand( ) % 256 ) ;
}
} ;
 
std::string deleteControls ( std::string startstring ) {
std::string noControls( " " ) ;//creating space for
//the standard algorithm remove_copy_if
std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) ,
ll_static_cast<int>( _1 ) < 32 && ll_static_cast<int>( _1 ) == 127 ) ;
return noControls ;
}
 
std::string deleteExtended( std::string startstring ) {
std::string noExtended ( " " ) ;//same as above
std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) ,
ll_static_cast<int>( _1 ) > 127 || ll_static_cast<int>( _1 ) < 32 ) ;
return noExtended ;
}
int main( ) {
std::string my_extended_string ;
for ( int i = 0 ; i < 40 ; i++ ) //we want the extended string to be 40 characters long
my_extended_string.append( " " ) ;
srand( time( 0 ) ) ;
std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ;
std::string no_controls( deleteControls( my_extended_string ) ) ;
std::string no_extended ( deleteExtended( my_extended_string ) ) ;
std::cout << "string with all characters: " << my_extended_string << std::endl ;
std::cout << "string without control characters: " << no_controls << std::endl ;
std::cout << "string without extended characters: " << no_extended << std::endl ;
return 0 ;
}</lang>
Output:
<PRE>string with all characters: K�O:~���7�5����
���W��@>��ȓ�q�Q@���W-
string without control characters: K�O:~���7�5����
���W��@>��ȓ�q�Q@���W-
string without extended characters: KO:~75W@>qQ@W-
</PRE>
=={{header|C sharp|C#}}==
Uses the test string from REXX.
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 411 ⟶ 697:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 418 ⟶ 704:
Stripped of extended: string of , may include control characters and other ilk.
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/casts.hpp>
#include <ctime>
#include <cstdlib>
using namespace boost::lambda ;
 
struct MyRandomizer {
char operator( )( ) {
return static_cast<char>( rand( ) % 256 ) ;
}
} ;
 
std::string deleteControls ( std::string startstring ) {
std::string noControls( " " ) ;//creating space for
//the standard algorithm remove_copy_if
std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) ,
ll_static_cast<int>( _1 ) < 32 && ll_static_cast<int>( _1 ) == 127 ) ;
return noControls ;
}
 
std::string deleteExtended( std::string startstring ) {
std::string noExtended ( " " ) ;//same as above
std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) ,
ll_static_cast<int>( _1 ) > 127 || ll_static_cast<int>( _1 ) < 32 ) ;
return noExtended ;
}
int main( ) {
std::string my_extended_string ;
for ( int i = 0 ; i < 40 ; i++ ) //we want the extended string to be 40 characters long
my_extended_string.append( " " ) ;
srand( time( 0 ) ) ;
std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ;
std::string no_controls( deleteControls( my_extended_string ) ) ;
std::string no_extended ( deleteExtended( my_extended_string ) ) ;
std::cout << "string with all characters: " << my_extended_string << std::endl ;
std::cout << "string without control characters: " << no_controls << std::endl ;
std::cout << "string without extended characters: " << no_extended << std::endl ;
return 0 ;
}</syntaxhighlight>
Output:
<PRE>string with all characters: K�O:~���7�5����
���W��@>��ȓ�q�Q@���W-
string without control characters: K�O:~���7�5����
���W��@>��ȓ�q�Q@���W-
string without extended characters: KO:~75W@>qQ@W-
</PRE>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">; generate our test string of characters with control and extended characters
(def range-of-chars (apply str (map char (range 256))))
 
Line 427 ⟶ 765:
 
; filter to return String of characters that are between 32 - 126:
(apply str (filter #(<= 32 (int %) 126) range-of-chars))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<pre>
<pre>> (defparameter *extended-ascii* (coerce (loop for i from 0 to 255 collect (code-char i)) 'string))
(defun control-char-p (ch)
(or (< (char-code ch) 32)
(= (char-code ch) 127)))
 
(defun extended-char-p (ch)
*EXTENDED-ASCII*
(> (char-code ch) 127))
> (defparameter *control-codes-stripped*
(remove-if #'(lambda (c)
(let ((x (char-code c)))
(or (< x 32) (= x 127))))
*extended-ascii*))
 
(defun strip-special-chars (string &key strip-extended)
*CONTROL-CODES-STRIPPED*
(let ((needs-removing-p (if strip-extended
> *control-codes-stripped*
(lambda (ch)
 
(or (control-char-p ch)
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
(extended-char-p ch)))
> (defparameter *control-codes-and-extended-stripped*
(remove-if-not #'(lambda (c) (and (standard-char-p c) (graphic #'control-char-p c)))
(remove-if needs-removing-p string)))
*extended-ascii*))
</pre>
 
*CONTROL-CODES-AND-EXTENDED-STRIPPED*
> *control-codes-and-extended-stripped*
 
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.traits;
 
S stripChars(S)(S s, bool function(dchar) pure nothrow mustStrip)
Line 471 ⟶ 804:
writeln(s.stripChars( c => isControl(c) || c == '\u007F' ));
writeln(s.stripChars( c => isControl(c) || c >= '\u007F' ));
}</langsyntaxhighlight>
{{out}}
<pre> abcédefabcédef�
abcédef
abcdef</pre>
 
 
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
{String pack with control and extened chars}
 
const TestStr ='N'+#$01 +'o'+#$02 +'w'+#$03 +' '+#$04 +'i'+#$05 +'s'+#$06 +' '+#$07 +'t'+#$08 +'h'+#$09 +'e'+#$0A +' '+#$0B +'t'+#$0C +'i'+#$0D +'m'+#$0E +'e'+#$0F +' '+#$10 +'f'+#$11 +'o'+#$12 +'r'+#$13 +' '+#$14 +'a'+#$15 +'l'+#$16 +'l'+#$17 +' '+#$18 +'g'+#$19 +'o'+#$1A +'o'+#$1B +'d'+#$1C +' '+#$1D +'m'+#$1E +'e'+#$1F +'n'+#$80 +' '+#$81 +'t'+#$82 +'o'+#$83 +' '+#$84 +'c'+#$85 +'o'+#$86 +'m'+#$87 +'e'+#$88 +' '+#$89 +'t'+#$8A +'o'+#$8B +' '+#$8C +'t'+#$8D +'h'+#$8E +'e'+#$8F +' '+#$90 +'a'+#$91 +'i'+#$92 +'d'+#$93 +' '+#$94 +'o'+#$95 +'f'+#$96 +' '+#$97 +'t'+#$98 +'h'+#$99 +'e'+#$9A +' '+#$9B +'p'+#$9C +'a'+#$9D +'r'+#$9E +'t'+#$9F +'y'+#$A0;
 
function StripControls(S: string): string;
{Strip control characters from string}
var I: integer;
begin
Result:='';
for I:=1 to Length(S) do
if byte(S[I])>=$20 then Result:=Result+S[I];
end;
 
function StripExtended(S: string): string;
{Strip extended characters from string}
var I: integer;
begin
Result:='';
for I:=1 to Length(S) do
if byte(S[I])<$80 then Result:=Result+S[I];
end;
 
 
procedure StripString(Memo: TMemo);
begin
Memo.Lines.Add('String full of controls and extended chars: ');
Memo.Lines.Add(TestStr);
Memo.Lines.Add('String stripped of controls chars: ');
Memo.Lines.Add(StripControls(TestStr));
Memo.Lines.Add('String stripped of extended chars: ');
Memo.Lines.Add(StripExtended(TestStr));
Memo.Lines.Add('String stripped of both control and extended chars: ');
Memo.Lines.Add(StripControls(StripExtended(TestStr)));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
String full of controls and extended chars:
N�o�w� �i�s� �t�h e
�t�i
m�e� �f�o�r� �a�l�l� �g�o�o�d� �m�e�n€ t‚oƒ „c…o†m‡eˆ ‰tŠo‹ ŒthŽe a‘i’d“ ”o•f– —t˜h™eš ›pœaržtŸy 
String stripped of controls chars:
Now is the time for all good men€ t‚oƒ „c…o†m‡eˆ ‰tŠo‹ ŒthŽe a‘i’d“ ”o•f– —t˜h™eš ›pœaržtŸy 
String stripped of extended chars:
N�o�w� �i�s� �t�h e
�t�i
m�e� �f�o�r� �a�l�l� �g�o�o�d� �m�e�n to come to the aid of the party
String stripped of both control and extended chars:
Now is the time for all good men to come to the aid of the party
Elapsed Time: 51.012 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang=easylang>
func$ strip s$ .
for c$ in strchars s$
if strcode c$ >= 32 and strcode c$ <= 126
r$ &= c$
.
.
return r$
.
print strip "\tHellö world"
</syntaxhighlight>
 
=={{header|Erlang}}==
Exported functions to be used by [[Update_a_configuration_file]]
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( strip_control_codes ).
 
Line 498 ⟶ 909:
String_without_cc_nor_ec = lists:filter( fun is_not_control_code_nor_extended_character/1, String ),
io:fwrite( "String without control codes nor extended characters (~p characters): ~s~n", [erlang:length(String_without_cc_nor_ec), String_without_cc_nor_ec] ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
41> strip_control_codes:task().
String (256 characters): ^@^A^B^C^D^E^F^G^H
^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\^]^^^_ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~^€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ�������������������������������� ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
String without control codes (223 characters): !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ�������������������������������� ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
String without control codes nor extended characters (95 characters): !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
</pre>
Line 510 ⟶ 921:
=={{header|F Sharp|F#}}==
Uses test string from REXX.
<langsyntaxhighlight lang="fsharp">
open System
 
Line 529 ⟶ 940:
printfn "Stripped of extended: %s" (stripExtended test)
0//main must return integer, much like in C/C++
</syntaxhighlight>
</lang>
Output:
<pre>
Original: string of ☺☻♥♦☺☻♥♦�, may include control characters and other ilk.♫☼§►↔◄
Stripped of controls: string of ☺☻♥♦☺☻♥♦�, may include control characters and other ilk.♫☼§►↔◄
Stripped of extended: string of , may include control characters and other ilk.
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: ascii kernel sequences ;
 
: strip-control-codes ( str -- str' ) [ control? not ] filter ;
 
: strip-control-codes-and-extended ( str -- str' )
strip-control-codes [ ascii? ] filter ;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: strip ( buf len -- buf len' ) \ repacks buffer, so len' <= len
over + over swap over ( buf dst limit src )
do
Line 553 ⟶ 964:
then
loop
over - ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">module stripcharacters
implicit none
 
Line 610 ⟶ 1,021:
write (*,*) strip(string,not_extended)
end program test
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function stripControlChars(s As Const String) As String
Line 690 ⟶ 1,101:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 703 ⟶ 1,114:
Ext chars stripped Length => 25
Both sets stripped Length => 19
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">stripExtended[str] := str =~ %s/[^\u0020-\u007e]//g
 
stripControl[str] := str =~ %s/[\u0000-\u001F\u007f]//g
 
println[stripExtended[char[0 to 127]]]
println[stripControl[char[0 to 127]]]</syntaxhighlight>
{{out}}
<pre>
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=19db658a6c44cfb1f6f887ff53e549bb Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String = "The\t \equick\n \fbrownfox \vcost £125.00 or €145.00 or $160.00 \bto \ncapture ©®"
Dim sStd, sExtend As String
Line 737 ⟶ 1,161:
Return sResult
 
End</langsyntaxhighlight>
Output:
<pre>
Line 751 ⟶ 1,175:
=={{header|Go}}==
Go works for ASCII and non-ASCII systems. The first pair of functions below interpret strings as byte strings, presumably useful for strings consisting of ASCII and 8-bit extended ASCII data. The second pair of functions interpret strings as UTF-8.
<langsyntaxhighlight lang="go">package main
 
import (
Line 840 ⟶ 1,264:
fmt.Println("\nas decomposed and stripped Unicode:")
fmt.Println(stripCtlAndExtFromUnicode(src))
}</langsyntaxhighlight>
Output: (varies with display configuration)
<pre>
source text:
déjà vu
� !~�����
as⃝df̅
 
Line 865 ⟶ 1,289:
 
=={{header|Groovy}}==
<langsyntaxhighlight Groovylang="groovy">def stripControl = { it.replaceAll(/\p{Cntrl}/, '') }
def stripControlAndExtended = { it.replaceAll(/[^\p{Print}]/, '') }</langsyntaxhighlight>
Test:
<langsyntaxhighlight Groovylang="groovy">def text = (0..255).collect { (char) it }.join('')
def textMinusControl = text.findAll { int v = (char)it; v > 31 && v != 127 }.join('')
def textMinusControlAndExtended = textMinusControl.findAll {((char)it) < 128 }.join('')
 
assert stripControl(text) == textMinusControl
assert stripControlAndExtended(text) == textMinusControlAndExtended</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Control.Applicative (liftA2)
 
strip, strip2 :: String -> String
strip = filter (liftA2 (&&) (> 31) (< 126) . fromEnum)
 
-- or
strip2 = filter (((&&) <$> (> 31) <*> (< 126)) . fromEnum)
 
main :: IO ()
main =
main = print $ strip "alphabetic 字母 with some less parochial parts"</lang>
(putStrLn . unlines) $
[strip, strip2] <*> ["alphabetic 字母 with some less parochial parts"]</syntaxhighlight>
{{Out}}
<pre>"alphabetic with some less parochial parts"</pre>
alphabetic with some less parochial parts</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
We'll use ''deletec'' to remove unwanted characters (2nd argument) from a string (1st argument). The procedure below coerces types back and forth between string and cset. The character set of unwanted characters is the difference of all ASCII characters and the ASCII characters from 33 to 126.
<langsyntaxhighlight Iconlang="icon">procedure main(A)
write(image(deletec(&ascii,&ascii--(&ascii)[33:127])))
end
link strings
</syntaxhighlight>
</lang>
 
{{libheader|Icon Programming Library}}
Line 898 ⟶ 1,328:
 
The IPL procedure ''deletec'' is equivalent to this:
<langsyntaxhighlight Iconlang="icon">procedure deletec(s, c) #: delete characters
result := ""
s ? {
Line 904 ⟶ 1,334:
return result ||:= tab(0)
}
end</langsyntaxhighlight>
 
 
Line 911 ⟶ 1,341:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">stripControlCodes=: -.&(DEL,32{.a.)
stripControlExtCodes=: ([ -. -.)&(32}.127{.a.)</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> mystring=: a. {~ ?~256 NB. ascii chars 0-255 in random order
#mystring NB. length of string
256
Line 928 ⟶ 1,358:
95
stripControlExtCodes myunicodestring
k}w:]U3xEh9"GZdr/#^B.Sn%\uFOo[(`t2-J6*IA=Vf&N;lQ8,${XLz5?D0~s)'Y7Kq|ip4<WRCaM!b@cgv_T +mH>1ejPy</langsyntaxhighlight>
 
Generally speaking, <code>([-.-.)</code> gives us the contents from the sequence on the left, restricted to only the items which appear in the sequence on the right.
 
[[Category:String manipulation]]
 
=={{header|Java}}==
{{works with|Java|8+}}
<syntaxhighlight lang="java">import java.util.function.IntPredicate;
 
public class StripControlCodes {
 
public static void main(String[] args) {
String s = "\u0000\n abc\u00E9def\u007F";
System.out.println(stripChars(s, c -> c > '\u001F' && c != '\u007F'));
System.out.println(stripChars(s, c -> c > '\u001F' && c < '\u007F'));
}
 
static String stripChars(String s, IntPredicate include) {
return s.codePoints().filter(include::test).collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
}</syntaxhighlight>
<pre> abcédef
abcdef</pre>
 
=={{header|JavaScript}}==
Line 936 ⟶ 1,388:
===ES 5===
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (strTest) {
 
// s -> s
Line 949 ⟶ 1,401:
return strip(strTest);
 
})("\ba\x00b\n\rc\fd\xc3");</langsyntaxhighlight>
 
{{Out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">"abcd"</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8+}}
<lang java>import java.util.function.IntPredicate;
 
public class StripControlCodes {
 
public static void main(String[] args) {
String s = "\u0000\n abc\u00E9def\u007F";
System.out.println(stripChars(s, c -> c > '\u001F' && c != '\u007F'));
System.out.println(stripChars(s, c -> c > '\u001F' && c < '\u007F'));
}
 
static String stripChars(String s, IntPredicate include) {
return s.codePoints().filter(include::test).collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
}</lang>
<pre> abcédef
abcdef</pre>
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def strip_control_codes:
explode | map(select(. > 31 and . != 127)) | implode;
 
def strip_extended_characters:
explode | map(select(31 < . and . < 127)) | implode;</langsyntaxhighlight>
 
'''Example''':
<langsyntaxhighlight lang="jq">def string: "string of ☺☻♥♦⌂, may include control characters such as null(\u0000) and other ilk.\n§►↔◄\nRødgrød med fløde";
 
"string | strip_control_codes\n => \(string | strip_control_codes)",
"string | strip_extended_characters\n => \(string | strip_extended_characters)"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -r -f Strip_control_codes_and_extended_characters.jq
string | strip_control_codes
=> string of ☺☻♥♦⌂, may include control characters such as null() and other ilk.§►↔◄Rødgrød med fløde
string | strip_extended_characters
=> string of , may include control characters such as null() and other ilk.Rdgrd med flde</langsyntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
stripc0{T<:String}(a::T) = replace(a, r"[\x00-\x1f\x7f]", "")
stripc0x{T<:String}(a::T) = replace(a, r"[^\x20-\x7e]", "")
Line 1,004 ⟶ 1,437:
println("\nWith C0 control characters removed:\n ", stripc0(a))
println("\nWith C0 and extended characters removed:\n ", stripc0x(a))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,020 ⟶ 1,453:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun String.strip(extendedChars: Boolean = false): String {
Line 1,041 ⟶ 1,474:
val u = s.strip(true)
println("String = $u Length = ${u.length}")
}</langsyntaxhighlight>
 
{{out}}
<pre>
Originally:
String = 123 abcDEFabcDEF�+-*/€æŧðłþ Length = 22
 
After stripping control characters:
Line 1,054 ⟶ 1,487:
String = 123abcDEF+-*/ Length = 13
</pre>
 
=={{header|langur}}==
<syntaxhighlight lang="langur">val .str = "()\x15abcd\uFFFF123\uBBBB!@#$%^&*\x01"
 
writeln "original : ", .str
writeln "without ctrl chars: ", replace(.str, RE/\p{Cc}/, "")
writeln "print ASCII only : ", replace(.str, re/[^ -~]/, "")</syntaxhighlight>
 
{{out}}
<pre>original : ()�abcd�123뮻!@#$%^&*�
without ctrl chars: ()abcd�123뮻!@#$%^&*
print ASCII only : ()abcd123!@#$%^&*</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
all$ =""
for i =0 to 255
Line 1,094 ⟶ 1,539:
extendedStripped$ =r$
end function
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Strip_Control_Codes( str )
local s = ""
for i in str:gmatch( "%C+" ) do
Line 1,121 ⟶ 1,566:
 
print( Strip_Control_Codes(q) )
print( Strip_Control_and_Extended_Codes(q) )</langsyntaxhighlight>
<pre> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">stripCtrl[x_]:=StringJoin[Select[Characters[x],
MemberQ[CharacterRange["!","~"]~Join~Characters[FromCharacterCode[Range[128,255]]],#]&]]
 
stripCtrlExt[x_]:=StringJoin[Select[Characters[x],
MemberQ[CharacterRange["!","~"],#]&]]</langsyntaxhighlight>
 
Test:
Line 1,137 ⟶ 1,582:
\.15\.16\.17\.18\.19\.1a\[RawEscape]\.1c\.1d\.1e\.1f !"#$%&'()*+,-./
0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ��������������������������������� ¡¢£¤¥¦§¨©ª«\[Not]­®¯\[Degree]
\[PlusMinus]\.b2\.b3\.b4\[Micro]\[Paragraph]\[CenterDot]¸¹º»¼½¾¿
ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ*ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö/øùúûüýþÿ
Line 1,143 ⟶ 1,588:
stripCtrl[CompleteSet]
->!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ�������������������������������� ¡¢£¤¥¦§¨©ª«\[Not]­®¯\[Degree]
\[PlusMinus]\.b2\.b3\.b4\[Micro]\[Paragraph]\[CenterDot]
¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ*ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö
Line 1,151 ⟶ 1,596:
->!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
^_`abcdefghijklmnopqrstuvwxyz{|}~</pre>
 
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight MATLABlang="matlab"> function str = stripped(str)
str = str(31<str & str<127);
end; </langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc stripped(str: string): string =
result = ""
for c in str:
Line 1,166 ⟶ 1,610:
result.add c
 
proc strippedControl(str: string): string =
echo stripped "\ba\x00b\n\rc\fd\xc3"</lang>
result = ""
for c in str:
if ord(c) in {32..126, 128..255}:
result.add c
 
echo strippedControl "\ba\x00b\n\rc\fdÄ"
echo stripped "\ba\x00b\n\rc\fd\xc3"</syntaxhighlight>
Output:
<pre>abcd</pre>abcdÄ
abcd</pre>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let is_control_code c =
letc d< ='\032' int_of_char|| c in= '\127'
 
d < 32 || d = 127
let is_extended_char c =
c > '\127'
let d = int_of_char c in
 
d > 127
let strip f str =
let len = String.length str in
Line 1,185 ⟶ 1,635:
let rec aux i j =
if i >= len
then Bytes.to_string (Bytes.subsub_string res 0 j)
else if f str.[i]
then aux (succ i) j
Line 1,194 ⟶ 1,644:
in
aux 0 0
 
let () =
Random.self_init ();
Line 1,203 ⟶ 1,653:
in
print_endline (strip is_control_code s);
print_endline (strip (fun c -> (is_control_code c) || (is_extended_char c)) s);</syntaxhighlight>
;;</lang>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">program StripCharacters(output);
 
function Strip (s: string; control, extended: boolean): string;
Line 1,233 ⟶ 1,682:
writeln ('No extnd: ', Strip(test, false, true));
writeln ('ASCII: ', Strip(test, true, true));
end.</langsyntaxhighlight>
Output:
<pre>% ./StripCharacters
Line 1,246 ⟶ 1,695:
=={{header|Peloton}}==
Peloton has a native instruction for removing control codes from a string, SAL, the Low ASCII Strip. From the manual:
<langsyntaxhighlight lang="sgml">Create variable with control characters: <@ SAYLETVARLIT>i|This string has control characters
- - - - - -
 
Line 1,253 ⟶ 1,702:
Assign infix <@ LETVARSALVAR>j|i</@> <@ SAYVAR>j</@>
Assign prepend <@ LETSALVARVAR>k|i</@> <@ SAYVAR>k</@>
Reflexive assign <@ ACTSALVAR>i</@> <@ SAYVAR>i</@></langsyntaxhighlight>
 
Peloton also has SAH, High ASCII Strip. Again, from the manual:
<langsyntaxhighlight lang="sgml">Create variable with high and low ANSI: <@ SAYLETVARLIT>i|This string has both low ansi and high ansi characters - il doit d'être prévenu</@>
Strip high ANSI <@ SAYSAHVAR>i</@>
Assign infix <@ LETVARSAHVAR>j|i</@> <@ SAYVAR>j</@>
Assign prepend <@ LETSAHVARVAR>k|i</@> <@ SAYVAR>k</@>
Reflexive assign <@ ACTSAHVAR>i</@> <@ SAYVAR>i</@></langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl -w
use strict ;
 
Line 1,281 ⟶ 1,730:
print "\nWithout extended: " ;
print join( '' , map { chr( $_ ) } @noextended ) ;
print "\n" ;</langsyntaxhighlight>
Output:
<PRE>before sanitation : �L08&YH�O��n)�:���O�G$���.���"zO���Q�?��
Line 1,287 ⟶ 1,736:
Without extended: L08&YHOn):OG$."zOQ?
</PRE>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2018.03}}
 
<lang perl6>my $str = (0..400).roll(80)».chr.join;
 
say $str;
say $str.subst(/<:Cc>/, '', :g); # unicode property: control character
say $str.subst(/<-[\ ..~]>/, '', :g);</lang>
<pre>kşaNĹĭŗ‘|Ęw�•�"ÄlĄWł8iCƁę��Ż�¬ž5ĎĶ'óü¸'ÍŸ;ŢƐ¦•´ŷQċűÒŴ$ÃŅ‰Đįð+=ĥƂ+Ōĭħ¼ŕc¤H~ìïēÕ
kşaNĹĭŗ|Ęw"ÄlĄWł8iCƁ꯬5ĎĶ'óü¸'ÍŸ;ŢƐ¦´ŷQċűÒŴ$ÃŅĐįð+=ĥƂ+Ōĭħ¼ŕc¤H~ìïēÕ
kaN|w"lW8iC5'';Q$+=+cH~</pre>
 
=={{header|Phix}}==
Line 1,304 ⟶ 1,741:
While you can delete a character from a string using say s[i..i] = "", the fastest and easiest way is always just
to build a new one character-by-character.<br>
I've credited Ada solely for the sensible fromch / toch / abovech idea.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function filter(string s, integer fromch=' ', toch=#7E, abovech=#7F)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
string res = ""
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (param default fixes in pwa/p2js)</span>
for i=1 to length(s) do
<span style="color: #008080;">function</span> <span style="color: #000000;">filter_it</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">fromch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">toch</span><span style="color: #0000FF;">=</span><span style="color: #000000;">#7E</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abovech</span><span style="color: #0000FF;">=</span><span style="color: #000000;">#7F</span><span style="color: #0000FF;">)</span>
integer ch = s[i]
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
if ch>=fromch and (ch<=toch or ch>abovech) then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
res &= ch
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">fromch</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">toch</span> <span style="color: #008080;">or</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #000000;">abovech</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end for
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">ch</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">put_line</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s \"%s\", Length:%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">full</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"\u0000 abc\u00E9def\u007F"</span>
<span style="color: #000000;">put_line</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"The full string:"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">full</span><span style="color: #0000FF;">)</span>
procedure put_line(string text, s)
<span style="color: #000000;">put_line</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"No Control Chars:"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">filter_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">full</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- default values for fromch, toch, and abovech</span>
printf(1,"%s \"%s\", Length:%d\n",{text,s,length(s)})
<span style="color: #000000;">put_line</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"\" and no Extended:"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">filter_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">full</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abovech</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">#FF</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- defaults for fromch and toch</span>
end procedure
<!--</syntaxhighlight>-->
string full = "\u0000 abc\u00E9def\u007F"
 
put_line("The full string:", full)
put_line("No Control Chars:", filter(full)) -- default values for fromch, toch, and abovech
put_line("\" and no Extended:", filter(full, abovech:=#FF)) -- defaults for fromch and toch</lang>
{{out}}
(desktop/Phix, in a grubby Windows console)
<pre>
The full string: " abc+®defdef�", Length:11
No Control Chars: " abc+®def", Length:9
" and no Extended: " abcdef", Length:7
</pre>
(pwa/p2js)
<pre>
The full string: " abcédef�", Length:10
No Control Chars: " abcédef", Length:8
" and no Extended: " abcdef", Length:7
</pre>
The reason is that JavaScript handles unicode slightly differently. On desktop/Phix, \u0000 is treated as the single ''byte'' #00, and
likewise \u007F as the single byte #7F, but \u00E9 is converted to the utf-8 sequence #C3,#A9 - hence the disagreement over the initial and middle lengths. For proper compatibility you would have to start playing with utf8_to_utf32() and friends. Also as you can see the grubby Windows console does not display utf8 nicely, so we get an ugly "+®" for what should be a single \u00E9 character. You should get slightly better results on a Linux console, and maybe if you have more fonts installed on Windows than I do, things might look better with a different one, plus of course the text is far more likely to display correctly in a GUI, but that's a bit beyond the remit of this simple task I fear.
 
=={{header|PicoLisp}}==
Control characters in strings are written with a hat (^) in PicoLisp. ^? is the DEL character.
<langsyntaxhighlight PicoLisplang="picolisp">(de stripCtrl (Str)
(pack
(filter
Line 1,345 ⟶ 1,795:
(filter
'((C) (> "^?" C "^_"))
(chop Str) ) ) )</langsyntaxhighlight>
Test:
<pre>: (char "^?")
Line 1,360 ⟶ 1,810:
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">> string input = random_string(100);
> (string)((array)input-enumerate(32)-enumerate(255-126,1,127));
Result: "p_xx08M]cK<FHgR3\\I.x>)Tm<VgakYddy&P7"</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
stripper: proc options (main);
declare s character (100) varying;
Line 1,431 ⟶ 1,881:
 
end stripper;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,441 ⟶ 1,891:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Remove-Character
{
Line 1,489 ⟶ 1,939:
}
}
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
$test = "$([char]9)Français."
 
Line 1,498 ⟶ 1,948:
"Extended characters stripped : `"$($test | Remove-Character -Extended)`""
"Control & extended stripped : `"$($test | Remove-Character)`""
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,506 ⟶ 1,956:
Control & extended stripped : "Franais."
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
"Français", "Čeština" | Remove-Character -Extended
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,516 ⟶ 1,966:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s stripControlCodes(source.s)
Protected i, *ptrChar.Character, length = Len(source), result.s
*ptrChar = @source
Line 1,553 ⟶ 2,003:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>»╫=┐C─≡G(═ç╤â√╝÷╔¬ÿ▌x  è4∞|)ï└⌐ƒ9²òτ┌ºáj)▓<~-vPÿφQ╨ù¿╖îFh"[ü╗dÉ₧q#óé├p╫■
Line 1,560 ⟶ 2,010:
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)
 
print(stripped("\ba\x00b\n\rc\fd\xc3"))</langsyntaxhighlight>Output:<syntaxhighlight lang="text">abcd</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
;; Works on both strings (Unicode) and byte strings (raw/ASCII)
Line 1,573 ⟶ 2,023:
(define (strip-controls-and-extended str)
(regexp-replace* #rx"[^\040-\176]+" str ""))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
 
<syntaxhighlight lang="raku" line>my $str = (0..400).roll(80)».chr.join;
 
say $str;
say $str.subst(/<:Cc>/, '', :g); # unicode property: control character
say $str.subst(/<-[\ ..~]>/, '', :g);</syntaxhighlight>
<pre>kşaNĹĭŗ�|Ęw���"ÄlĄWł8iCƁę��Ż�¬�5ĎĶ'óü¸'ÍŸ;ŢƐ¦�´ŷQċűÒŴ$ÃŅ�Đįð+=ĥƂ+Ōĭħ¼ŕc¤H~ìïēÕ
kşaNĹĭŗ|Ęw"ÄlĄWł8iCƁ꯬5ĎĶ'óü¸'ÍŸ;ŢƐ¦´ŷQċűÒŴ$ÃŅĐįð+=ĥƂ+Ōĭħ¼ŕc¤H~ìïēÕ
kaN|w"lW8iC5'';Q$+=+cH~</pre>
 
=={{header|REXX}}==
Line 1,579 ⟶ 2,042:
===idiomatic version===
This REXX version processes each character in an idiomatic way &nbsp; (if it's a wanted character, then keep it).
<langsyntaxhighlight lang="rexx">/*REXX program strips all "control codes" from a character string (ASCII or EBCDIC). */
z= 'string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.'
@=' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
Line 1,588 ⟶ 2,051:
 
say 'old = »»»'z"«««" /*add ««fence»» before & after old text*/
say 'new = »»»'$"«««" /* " " " " " new " */</langsyntaxhighlight>
{{out|output}}
<pre>
Line 1,601 ⟶ 2,064:
 
Because there are &nbsp; (or should be) &nbsp; fewer unwanted characters than wanted characters, this version is faster.
<langsyntaxhighlight lang="rexx">/*REXX program strips all "control codes" from a character string (ASCII or EBCDIC). */
x= 'string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.'
@=' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij' || ,
Line 1,611 ⟶ 2,074:
 
say 'old = »»»' || x || "«««" /*add ««fence»» before & after old text*/
say 'new = »»»' || $ || "«««" /* " " " " " new " */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
s = char(31) + "abc" + char(13) + "def" + char(11) + "ghi" + char(10)
see strip(s) + nl
Line 1,628 ⟶ 2,091:
next
return strip
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
RPL has a character set based on ASCII but does not support extended characters.
≪ → text
≪ "" 1 text SIZE '''FOR''' j
text j DUP SUB NUM
'''IF''' DUP 32 ≥ OVER 126 ≤ '''THEN''' CHR + '''ELSE''' DROP '''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">NOCTRL</span>' STO
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class String
def strip_control_characters()
chars.each_with_object("") do |char, str|
Line 1,647 ⟶ 2,119:
p s = "\ba\x00b\n\rc\fd\xc3\x7ffoo"
p s.strip_control_characters
p s.strip_control_and_extended_characters</langsyntaxhighlight>
 
{{out}}
Line 1,655 ⟶ 2,127:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">s$ = chr$(31) + "abc" + chr$(13) + "def" + chr$(11) + "ghi" + chr$(10)
print strip$(s$)
 
Line 1,675 ⟶ 2,147:
end if
next i
END FUNCTION</langsyntaxhighlight>
<pre>
input : chr$(31)+"abc"+chr$(13)+"def"+chr$(11)+"ghi"+chr$(10)
output : abcdefghi</pre>
 
 
=={{header|Scala}}==
===ASCII: Using StringOps Class===
<langsyntaxhighlight Scalalang="scala">val controlCode : (Char) => Boolean = (c:Char) => (c <= 32 || c == 127)
val extendedCode : (Char) => Boolean = (c:Char) => (c <= 32 || c > 127)
 
Line 1,694 ⟶ 2,165:
 
println( "ctrl and extended filtered out: \n\n" +
teststring.filterNot(controlCode).filterNot(extendedCode) + "\n" )</langsyntaxhighlight>
{{out}}
<pre>ctrl filtered out:
Line 1,710 ⟶ 2,181:
 
===Unicode: Using Regular Expressions===
<syntaxhighlight lang="scala">//
<lang Scala>//
// A Unicode test string
//
Line 1,729 ⟶ 2,200:
val htmlNoExtCode = for( i <- sNoExtCode.indices ) yield
"&#" + sNoExtCode(i).toInt + ";" + (if( (i+1) % 10 == 0 ) "\n" else "")
println( "ctrl and extended filtered out: <br/><br/>\n\n" + htmlNoExtCode.mkString + "<br/><br/>\n" )</langsyntaxhighlight>
{{out}}
<pre>ctrl filtered out:
Line 1,761 ⟶ 2,232:
&#32;&#68;&#113;&#49;&#91;&#58;&#51;&#83;&#80;&#77;&#110;&#67;&#90;&#60;&#74;&#43;&#102;&#117;&#34;&#93;&#109;&#92;&#50;&#54;&#124;&#106;&#85;&#64;&#101;&#96;&#78;&#63;&#95;&#39;&#75;&#126;&#112;&#115;&#46;&#98;&#105;&#72;&#55;&#62;&#122;&#65;&#88;&#86;&#70;&#53;
&#61;&#79;&#103;&#66;&#104;&#89;&#71;&#99;&#45;&#52;&#41;&#69;&#47;&#42;&#97;&#44;&#37;&#119;&#84;&#76;&#111;&#82;&#38;&#87;&#123;&#107;&#100;&#125;&#56;&#108;&#94;&#59;&#48;&#35;&#40;&#33;&#116;&#114;&#118;&#73;&#120;&#36;&#81;&#121;&#57;</pre>
 
=={{header|sed}}==
To strip control codes only:
<syntaxhighlight lang="sed">s/[[:cntrl:]]//g</syntaxhighlight>
To strip control codes and extended characters:
<syntaxhighlight lang="sed">s/[^[:print:]]//g</syntaxhighlight>
For this to work properly with sed implementations supporting multibyte character encodings (like UTF-8), the environment variable LC_ALL=C might need to be set.
{{out}}
<pre>
$ printf 'Just\tä\tString\n' | LC_ALL=C sed 's/[[:cntrl:]]//g'
JustäString
$ printf 'Just\tä\tString\n' | LC_ALL=C sed 's/[^[:print:]]//g'
JustString
</pre>
 
=={{header|Seed7}}==
Line 1,769 ⟶ 2,254:
Unicode characters with UTF-8 encoding to the console.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "utf8.s7i";
 
Line 1,819 ⟶ 2,304:
writeln("Stripped of control codes and extended characters:");
writeln(stripControlAndExtended(src));
end func;</langsyntaxhighlight>
 
Output:
Line 1,825 ⟶ 2,310:
source text:
déjà vu
� !~€ÿ��ÿ
as⃝df̅
Stripped of control codes:
déjà vu !~€ÿas⃝df̅�ÿas⃝df̅
Stripped of control codes and extended characters:
dj vu !~asdf
Line 1,834 ⟶ 2,319:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var str = "\ba\x00b\n\rc\fd\xc3\x7ffoo"
 
var letters = str.chars.map{.ord}
Line 1,843 ⟶ 2,328:
 
var noextended = nocontrols.grep{ _ < 127 }
say noextended.map{.chr}.join.dump</langsyntaxhighlight>
{{out}}
<pre>
Line 1,850 ⟶ 2,335:
"abcdfoo"
</pre>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">(* string -> string *)
val stripCntrl = concat o String.tokens Char.isCntrl
 
(* string -> string *)
val stripCntrlAndExt = concat o String.tokens (not o Char.isPrint)</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc stripAsciiCC str {
regsub -all {[\u0000-\u001f\u007f]+} $str ""
}
proc stripCC str {
regsub -all {[^\u0020-\u007e]+} $str ""
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 1,864 ⟶ 2,356:
The following "normal characters" do exist, but can't be typed on the calculator and a hex editor must be used to enter them:
 
<syntaxhighlight lang ="ti83b">#$&@;_`abcdefghijklmnopqrstuvwxyz|~</langsyntaxhighlight>
 
The double quote character (ASCII decimal 34) can be entered, but cannot be escaped and thus cannot be stored to strings without the use of hex editors. The following program will remove double quotes from the input string if they were hacked in simply because having one stored to the "check" string is syntactically invalid.
Line 1,870 ⟶ 2,362:
So, in sum, you have to hack the calculator to enter in this program, but once it's entered you can transfer it to unhacked calculators and it will work.
 
<langsyntaxhighlight lang="ti83b">:" !#$%&'()*+,-./0123456789:;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"→Str0
:Input ">",Str1
:":"+Str1+":"→Str1
Line 1,878 ⟶ 2,370:
:End
:sub(Str1,2,length(Str1)-1)→Str1
:Pause Str1</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 1,884 ⟶ 2,376:
{{trans|Racket}}
 
<langsyntaxhighlight lang="txrlisp">(defun strip-controls (str)
(regsub #/[\x0-\x1F\x7F]+/ "" str))
 
(defun strip-controls-and-extended (str)
(regsub #/[^\x20-\x7F]+/ "" str))</langsyntaxhighlight>
 
=={{header|VBScript}}==
Derived from the BASIC version.
<syntaxhighlight lang="vb">
<lang vb>
Function StripCtrlCodes(s)
tmp = ""
Line 1,915 ⟶ 2,407:
End Function
 
WScript.StdOut.Write "ab�cd�ef�gh€ab�cd�ef�gh�€" & " = " & StripCtrlCodes("ab�cd�ef�gh€ab�cd�ef�gh�€")
WScript.StdOut.WriteLine
WScript.StdOut.Write "ab�cd�ef�ghij†klð€ab�cd�ef�gh�ij†klð€" & " = " & StripCtrlCodesExtChrs("ab�cd�ef�ghij†klð€ab�cd�ef�gh�ij†klð€")
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
<pre>
ab�cd�ef�gh€ab�cd�ef�gh�€ = abcdefgh€
ab�cd�ef�ghij†klð€ab�cd�ef�gh�ij†klð€ = abcdefghijkl
</pre>
 
=={{header|V (Vlang)}}==
{{trans|AutoHotkey}}
<syntaxhighlight lang="v (vlang)">fn main() {
println(stripped("\ba\x00b\n\rc\fd\xc3"))
}
 
fn stripped(source string) string {
mut result := ''
for value in source {if value > 31 && value < 128 {result += value.ascii_str()}}
return result
}</syntaxhighlight>
 
{{Out}}
<pre>
abcd
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-pattern}}
<syntaxhighlight lang="wren">import "./pattern" for Pattern
 
var s = "\t\n\r\x01\0\fabc\v\v\b\a\x1f\x7f🌇Páez😃É"
 
// strip control codes only
var p = Pattern.new("+1/c")
var r = p.replaceAll(s, "")
System.print("%(r) -> length %(r.count)")
 
// strip extended characters as well
p = Pattern.new("[+1/c|+1/R]")
r = p.replaceAll(s, "")
System.print("%(r) -> length %(r.count)")
</syntaxhighlight>
 
{{out}}
<pre>
abc🌇Páez😃É -> length 10
abcPez -> length 6
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
 
Line 1,956 ⟶ 2,488:
Strip(String, true);
Text(0, String); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 1,968 ⟶ 2,500:
=={{header|zkl}}==
ASCII
<langsyntaxhighlight lang="zkl">var ctlCodes=([1..31].pump(String,"toChar") +(127).toChar());
var extdChars=[127..255].pump(String,"toChar");
 
Line 1,976 ⟶ 2,508:
(test-extdChars).println("<< no extended chars");
(test-extdChars-ctlCodes).println("<< text");
</syntaxhighlight>
</lang>
{{out}}
<pre>
9,476

edits