Remove vowels from a string
Remove vowels from a string
ALGOL 68
<lang algol68>BEGIN
# returns s with the vowels removed # OP DEVOWEL = ( STRING s )STRING: BEGIN [ LWB s : UPB s ]CHAR result; INT r pos := LWB result - 1; FOR s pos FROM LWB s TO UPB s DO IF NOT char in string( s[ s pos ], NIL, "aeiouAEIOU" ) THEN # have a non-vowel - add it to the output # r pos +:= 1; result[ r pos ] := s[ s pos ] FI OD; result[ LWB s : r pos ] END # DEVOWEL # ; # tests the DEVOWEL operator # PROC test devowel = ( STRING s )VOID: print( ( "<", s, "> -> <", DEVOWEL s, ">", newline ) ); # some test cases # test devowel( "" ); test devowel( "aAeEiIoOuU" ); test devowel( "bcdfghjklmnprstvwxyz" ); test devowel( "abcdefghijklmnoprstuvwxyz" ); test devowel( "Algol 68 Programming Language" )
END</lang>
- Output:
<> -> <> <aAeEiIoOuU> -> <> <bcdfghjklmnprstvwxyz> -> <bcdfghjklmnprstvwxyz> <abcdefghijklmnoprstuvwxyz> -> <bcdfghjklmnprstvwxyz> <Algol 68 Programming Language> -> <lgl 68 Prgrmmng Lngg>
AppleScript
Removing three particular Anglo-Saxon vowels from a text.
AppleScript doesn't provide list comprehensions, and even use of regular expressions requires the study of a Foreign Function Interface to ObjC, which might be thought to defeat the goals of an entry-level scripting language.
We can at least use the universally available list monad (using a general concatMap as the bind operator here, and returning an empty list in place of any excluded glyph).
We can also improve productivity by using library functions whenever feasible.
<lang applescript>------- REMOVE A DEFINED SUBSET OF GLYPHS FROM A TEXT ------
-- exceptGlyphs :: String -> String -> Bool on exceptGlyphs(exclusions, s)
script go on |λ|(c) if exclusions contains c then {} else {c} end if end |λ| end script concatMap(go, s)
end exceptGlyphs
-- Or, in terms of a general filter function:
-- exceptGlyphs2 :: String -> String -> Bool on exceptGlyphs2(exclusions, s)
script p on |λ|(c) exclusions does not contain c end |λ| end script filter(p, s)
end exceptGlyphs2
TEST --------------------------
on run
set txt to unlines({¬ "Rosetta Code is a programming chrestomathy site. ", ¬ "The idea is to present solutions to the same ", ¬ "task in as many different languages as possible, ", ¬ "to demonstrate how languages are similar and ", ¬ "different, and to aid a person with a grounding ", ¬ "in one approach to a problem in learning another."}) exceptGlyphs("eau", txt)
end run
LIBRARY FUNCTIONS --------------------
-- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs)
set lng to length of xs set acc to {} tell mReturn(f) repeat with i from 1 to lng set acc to acc & (|λ|(item i of xs, i, xs)) end repeat end tell if {text, string} contains class of xs then acc as text else acc end if
end concatMap
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(p, xs)
tell mReturn(p) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat if {text, string} contains class of xs then lst as text else lst end if end tell
end filter
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if
end mReturn
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s
end unlines</lang>
- Output:
Rostt Cod is progrmming chrstomthy sit. Th id is to prsnt soltions to th sm tsk in s mny diffrnt lnggs s possibl, to dmonstrt how lnggs r similr nd diffrnt, nd to id prson with gronding in on pproch to problm in lrning nothr.
AutoHotkey
<lang AutoHotkey>str := "The quick brown fox jumps over the lazy dog" for i, v in StrSplit("aeiou") str := StrReplace(str, v) MsgBox % str</lang>
- Output:
Th qck brwn fx jmps vr th lzy dg
RegEx Version
<lang AutoHotkey>str := "The quick brown fox jumps over the lazy dog" MsgBox % str := RegExReplace(str, "i)[aeiou]")</lang>
- Output:
Th qck brwn fx jmps vr th lzy dg
C
<lang c>#include <stdio.h>
void print_no_vowels(const char *s) {
for (; *s != 0; s++) { switch (*s) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': break; default: putchar(*s); break; } }
}
void test(const char *const s) {
printf("Input : %s\n", s);
printf("Output : "); print_no_vowels(s); printf("\n");
}
int main() {
test("C Programming Language"); return 0;
}</lang>
- Output:
Input : C Programming Language Output : C Prgrmmng Lngg
Delphi
<lang Delphi> program Remove_vowels_from_a_string;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
function RemoveVowels(const s: string): string; const
VOWELS =['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
var
c: char;
begin
Result := ; for c in s do begin if not (c in VOWELS) then Result := Result + c; end;
end;
const
TEST = 'The quick brown fox jumps over the lazy dog';
begin
Writeln('Before: ', TEST); Writeln('After: ', RemoveVowels(TEST)); Readln;
end.
</lang>
- Output:
Before: The quick brown fox jumps over the lazy dog After: Th qck brwn fx jmps vr th lzy dg
F#
<lang fsharp> let stripVowels n=let g=set['a';'e';'i';'o';'u';'A';'E';'I';'O';'U'] in n|>Seq.filter(fun n->not(g.Contains n))|>Array.ofSeq|>System.String printfn "%s" (stripVowels "Nigel Galloway") </lang>
- Output:
"Ngl Gllwy"
Factor
<lang factor>USING: formatting kernel sets ;
- without-vowels ( str -- new-str ) "aeiouAEIOU" without ;
"Factor Programming Language" dup without-vowels " Input string: %s\nWithout vowels: %s\n" printf</lang>
- Output:
Input string: Factor Programming Language Without vowels: Fctr Prgrmmng Lngg
Go
<lang go>package main
import (
"fmt" "strings"
)
func removeVowels(s string) string {
var sb strings.Builder vowels := "aeiouAEIOU" for _, c := range s { if !strings.ContainsAny(string(c), vowels) { sb.WriteRune(c) } } return sb.String()
}
func main() {
s := "Go Programming Language" fmt.Println("Input :", s) fmt.Println("Output :", removeVowels(s))
}</lang>
- Output:
Input : Go Programming Language Output : G Prgrmmng Lngg
Haskell
Removing three specific Anglo-Saxon vowels from a text, using a general method which can apply to any specific subset of glyphs.
( Pace Jamie Kawinski, some people, when confronted with a problem, think "I know, I'll use list comprehensions." ) <lang haskell>------ REMOVE A SPECIFIC SUBSET OF GLYPHS FROM A STRING ----
exceptGlyphs :: String -> String -> String exceptGlyphs exclusions s =
[ c | c <- s , c `notElem` exclusions ]
TEST --------------------------
txt :: String txt =
"Rosetta Code is a programming chrestomathy site.\n\ \The idea is to present solutions to the same\n\ \task in as many different languages as possible,\n\ \to demonstrate how languages are similar and\n\ \different, and to aid a person with a grounding\n\ \in one approach to a problem in learning another."
main :: IO () main = putStrLn $ exceptGlyphs "eau" txt</lang>
or, in terms of filter: <lang haskell>exceptGlyphs :: String -> String -> String exceptGlyphs = filter . flip notElem</lang>
- Output:
Rostt Cod is progrmming chrstomthy sit. Th id is to prsnt soltions to th sm tsk in s mny diffrnt lnggs s possibl, to dmonstrt how lnggs r similr nd diffrnt, nd to id prson with gronding in on pproch to problm in lrning nothr.
JavaScript
Removing all instances of three particular vowels from a text, using an approach that is generalisable to the removal of any specified subset of glyphs.
( Pace Jamie Zawinski, some people, when confronted with a problem, think "I know, I'll use parser combinators." )
<lang javascript>(() => {
'use strict'
// Parser :: String -> Parser String const purgedText = exclusions => fmapP(concatMap(concat))( sepBy( some(noneOf(exclusions)) )( some(oneOf(exclusions)) ) );
// ----------------------- TEST ------------------------ const main = () => { const txt = ` Rosetta Code is a programming chrestomathy site. The idea is to present solutions to the same task in as many different languages as possible, to demonstrate how languages are similar and different, and to aid a person with a grounding in one approach to a problem in learning another.`
return fst(parse( purgedText('eau') )(txt)[0]); };
// ---------------- PARSER COMBINATORS -----------------
// Parser :: String -> [(a, String)] -> Parser a const Parser = f => // A function lifted into a Parser object. ({ type: 'Parser', parser: f });
// altP (<|>) :: Parser a -> Parser a -> Parser a const altP = p => // p, or q if p doesn't match. q => Parser(s => { const xs = p.parser(s); return 0 < xs.length ? ( xs ) : q.parser(s); });
// apP <*> :: Parser (a -> b) -> Parser a -> Parser b const apP = pf => // A new parser obtained by the application // of a Parser-wrapped function, // to a Parser-wrapped value. p => Parser( s => pf.parser(s).flatMap( vr => fmapP(vr[0])( p ).parser(vr[1]) ) );
// bindP (>>=) :: Parser a -> // (a -> Parser b) -> Parser b const bindP = p => // A new parser obtained by the application of // a function to a Parser-wrapped value. // The function must enrich its output, lifting it // into a new Parser. // Allows for the nesting of parsers. f => Parser( s => p.parser(s).flatMap( tpl => f(tpl[0]).parser(tpl[1]) ) );
// fmapP :: (a -> b) -> Parser a -> Parser b const fmapP = f => // A new parser derived by the structure-preserving // application of f to the value in p. p => Parser( s => p.parser(s).flatMap( vr => Tuple(f(vr[0]))(vr[1]) ) );
// liftA2P :: (a -> b -> c) -> // Parser a -> Parser b -> Parser c const liftA2P = op => // The binary function op, lifted // to a function over two parsers. p => apP(fmapP(op)(p));
// many :: Parser a -> Parser [a] const many = p => { // Zero or more instances of p. // Lifts a parser for a simple type of value // to a parser for a list of such values. const some_p = p => liftA2P( x => xs => [x].concat(xs) )(p)(many(p)); return Parser( s => ( 0 < s.length ? ( altP(some_p(p))(pureP([])) ) : pureP([]) ).parser(s) ); };
// noneOf :: String -> Parser Char const noneOf = s => // Any character not found in the // exclusion string. satisfy(c => !s.includes(c));
// oneOf :: [Char] -> Parser Char const oneOf = s => // One instance of any character found // the given string. satisfy(c => s.includes(c));
// parse :: Parser a -> String -> [(a, String)] const parse = p => // The result of parsing s with p. s => p.parser(s);
// pureP :: a -> Parser a const pureP = x => // The value x lifted, unchanged, // into the Parser monad. Parser(s => [Tuple(x)(s)]);
// satisfy :: (Char -> Bool) -> Parser Char const satisfy = test => // Any character for which the // given predicate returns true. Parser( s => 0 < s.length ? ( test(s[0]) ? [ Tuple(s[0])(s.slice(1)) ] : [] ) : [] );
// sepBy :: Parser a -> Parser b -> Parser [a] const sepBy = p => // Zero or more occurrences of p, as // separated by (discarded) instances of sep. sep => altP( sepBy1(p)(sep) )( pureP([]) );
// sepBy1 :: Parser a -> Parser b -> Parser [a] const sepBy1 = p => // One or more occurrences of p, as // separated by (discarded) instances of sep. sep => bindP( p )(x => bindP( many(bindP( sep )(_ => bindP( p )(pureP))))( xs => pureP([x].concat(xs))));
// some :: Parser a -> Parser [a] const some = p => { // One or more instances of p. // Lifts a parser for a simple type of value // to a parser for a list of such values. const many_p = p => altP(some(p))(pureP([])); return Parser( s => liftA2P( x => xs => [x].concat(xs) )(p)(many_p(p)).parser(s) ); };
// ----------------- GENERIC FUNCIONS ------------------
// Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 });
// concat :: a -> [a] // concat :: [String] -> String const concat = xs => ( ys => 0 < ys.length ? ( ys.every(Array.isArray) ? ( [] ) : ).concat(...ys) : ys )(xs);
// concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = f => // Where (a -> [b]) returns an Array, this // is equivalent to .flatMap, which should be // used by default. // but if (a -> [b]) returns String rather than [Char], // the monoid unit is in place of [], and a // concatenated string is returned. xs => { const ys = list(xs).map(f); return 0 < ys.length ? ( ys.some(y => 'string' !== typeof y) ? ( [] ) : ).concat(...ys) : ys; };
// list :: StringOrArrayLike b => b -> [a] const list = xs => // xs itself, if it is an Array, // or an Array derived from xs. Array.isArray(xs) ? ( xs ) : Array.from(xs || []);
// map :: (a -> b) -> [a] -> [b] const map = f => // The list obtained by applying f // to each element of xs. // (The image of xs under f). xs => [...xs].map(f);
// fst :: (a, b) -> a const fst = tpl => // First member of a pair. tpl[0];
// main --- return main();
})();</lang>
- Output:
Rostt Cod is progrmming chrstomthy sit. Th id is to prsnt soltions to th sm tsk in s mny diffrnt lnggs s possibl, to dmonstrt how lnggs r similr nd diffrnt, nd to id prson with gronding in on pproch to problm in lrning nothr.
Julia
Unicode sensitive, using the Raku version example text. <lang julia>const ALLVOWELS = Dict(ch => 1 for ch in Vector{Char}("AÀÁÂÃÄÅĀĂĄǺȀȂẠẢẤẦẨẪẬẮẰẲẴẶḀÆǼEȄȆḔḖḘḚḜẸẺẼẾỀỂỄỆĒĔĖĘĚÈÉÊËIȈȊḬḮỈỊĨĪĬĮİÌÍÎÏIJOŒØǾȌȎṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢŌÒÓŎŐÔÕÖUŨŪŬŮŰŲÙÚÛÜȔȖṲṴṶṸṺỤỦỨỪỬỮỰ")) const ALLVOWELSY = Dict(ch => 1 for ch in Vector{Char}("AÀÁÂÃÄÅĀĂĄǺȀȂẠẢẤẦẨẪẬẮẰẲẴẶḀÆǼEȄȆḔḖḘḚḜẸẺẼẾỀỂỄỆĒĔĖĘĚÈÉÊËIȈȊḬḮỈỊĨĪĬĮİÌÍÎÏIJOŒØǾȌȎṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢŌÒÓŎŐÔÕÖUŨŪŬŮŰŲÙÚÛÜȔȖṲṴṶṸṺỤỦỨỪỬỮỰYẙỲỴỶỸŶŸÝ"))
isvowel(ch, yisavowel=false) = haskey(yisavowel ? ALLVOWELSY : ALLVOWELS, uppercase(ch))
const testtext = """
Norwegian, Icelandic, German, Turkish, French, Spanish, English: Undervisningen skal være gratis, i det minste på de elementære og grunnleggende trinn. Skal hún veitt ókeypis, að minnsta kosti barnafræðsla og undirstöðummentu. Hochschulunterricht muß allen gleichermaßen entsprechend ihren Fähigkeiten offenstehen. Öğrenim hiç olmazsa ilk ve temel safhalarında parasızdır. İlk öğretim mecburidir. L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada. Education shall be free, at least in the elementary and fundamental stages."""
println("Removing vowels from:\n$testtext\n becomes:\n",
String(filter(!isvowel, Vector{Char}(testtext))))
</lang>
- Output:
Removing vowels from: Norwegian, Icelandic, German, Turkish, French, Spanish, English: Undervisningen skal være gratis, i det minste på de elementære og grunnleggende trinn. Skal hún veitt ókeypis, að minnsta kosti barnafræðsla og undirstöðummentu. Hochschulunterricht muß allen gleichermaßen entsprechend ihren Fähigkeiten offenstehen. Öğrenim hiç olmazsa ilk ve temel safhalarında parasızdır. İlk öğretim mecburidir. L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada. Education shall be free, at least in the elementary and fundamental stages. becomes: Nrwgn, clndc, Grmn, Trksh, Frnch, Spnsh, nglsh: ndrvsnngn skl vr grts, dt mnst p d lmntr g grnnlggnd trnn. Skl hn vtt kyps, ð mnnst kst brnfrðsl g ndrstðmmnt. Hchschlntrrcht mß lln glchrmßn ntsprchnd hrn Fhgktn ffnsthn. ğrnm hç lmzs lk v tml sfhlrnd prszdr. lk ğrtm mcbrdr. L'dctn dt tr grtt, mns n c q cncrn l'nsgnmnt lmntr t fndmntl. L nstrccn lmntl sr blgtr. L nstrccn tcnc y prfsnl hbr d sr gnrlzd. dctn shll b fr, t lst n th lmntry nd fndmntl stgs.
Perl
Inspired by the Raku entry. <lang perl>use strict; use warnings; use utf8; binmode STDOUT, ":utf8"; use Unicode::Normalize;
my $text = <<~'END';
Norwegian, Icelandic, German, Turkish, French, Spanish, English: Undervisningen skal være gratis, i det minste på de elementære og grunnleggende trinn. Skal hún veitt ókeypis, að minnsta kosti barnafræðsla og undirstöðummentu. Hochschulunterricht muß allen gleichermaßen entsprechend ihren Fähigkeiten offenstehen. Öğrenim hiç olmazsa ilk ve temel safhalarında parasızdır. İlk öğretim mecburidir. L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada. Education shall be free, at least in the elementary and fundamental stages. END
my @vowels; chr($_) =~ /[aæeiıoœu]/i and push @vowels, chr($_) for 0x20 .. 0x1ff; print NFD($_) =~ /@{[join '|', @vowels]}/ ? ' ' : $_ for split /(\X)/, $text;</lang>
- Output:
N rw g n, c l nd c, G rm n, T rk sh, Fr nch, Sp n sh, ngl sh: nd rv sn ng n sk l v r gr t s, d t m nst p d l m nt r g gr nnl gg nd tr nn. Sk l h n v tt k yp s, ð m nnst k st b rn fr ðsl g nd rst ð mm nt . H chsch l nt rr cht m ß ll n gl ch rm ß n ntspr ch nd hr n F h gk t n ff nst h n. ğr n m h ç lm zs lk v t m l s fh l r nd p r s zd r. lk ğr t m m cb r d r. L' d c t n d t tr gr t t , m ns n c q c nc rn l' ns gn m nt l m nt r t f nd m nt l. L nstr cc n l m nt l s r bl g t r . L nstr cc n t cn c y pr f s n l h br d s r g n r l z d . d c t n sh ll b fr , t l st n th l m nt ry nd f nd m nt l st g s.
Phix
<lang Phix>function not_vowel(integer ch)
return find(lower(ch),"aeiou")=0
end function constant s = "Phix Programming Language" printf(1,"Input : %s\nOutput : %s\n",{s,filter(s,not_vowel)})</lang>
- Output:
Input : Phix Programming Language Output : Phx Prgrmmng Lngg
If you want something a bit more like Julia/Raku, the following should work, but you have to provide your own vowel-set, or nick/merge from Julia/REXX <lang Phix>constant vowels = utf8_to_utf32("AEIOUİÖaeiouæáåäéêıóöú"), s = """ Norwegian, Icelandic, German, Turkish, French, Spanish, English: Undervisningen skal være gratis, i det minste på de elementære og grunnleggende trinn. Skal hún veitt ókeypis, að minnsta kosti barnafræðsla og undirstöðummentu. Hochschulunterricht muß allen gleichermaßen entsprechend ihren Fähigkeiten offenstehen. Öğrenim hiç olmazsa ilk ve temel safhalarında parasızdır. İlk öğretim mecburidir. L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada. Education shall be free, at least in the elementary and fundamental stages. """
function remove_vowels(sequence s)
s = utf8_to_utf32(s) for i=length(s) to 1 by -1 do if find(s[i],vowels) then s[i] = ' ' end if
-- if find(s[i],vowels) then s[i..i] = "" end if
end for s = utf32_to_utf8(s) return s
end function printf(1,"%s\n",remove_vowels(s))</lang> (output deliberately not shown due to windows console effects, but it is the same as Raku, or Julia with the alternate find/replace line.)
Python
Removing 3 particular Anglo-Saxon vowels from a string:
<lang python>Remove a defined subset of glyphs from a string
- exceptGlyphs :: String -> String -> String
def exceptGlyphs(exclusions):
A string from which all instances of a given set of glyphs have been removed. def go(s): return .join([ c for c in s if c not in exclusions ]) return go
- -------------------------- TEST --------------------------
- main :: IO ()
def main():
Test
txt = Rosetta Code is a programming chrestomathy site. The idea is to present solutions to the same task in as many different languages as possible, to demonstrate how languages are similar and different, and to aid a person with a grounding in one approach to a problem in learning another.
print( exceptGlyphs('eau')(txt) )
- MAIN ---
if __name__ == '__main__':
main()</lang>
- Output:
Rostt Cod is progrmming chrstomthy sit. Th id is to prsnt soltions to th sm tsk in s mny diffrnt lnggs s possibl, to dmonstrt how lnggs r similr nd diffrnt, nd to id prson with gronding in on pproch to problm in lrning nothr.
Raku
Not going to bother with 'y', it's too touchy feely (How many vowels are in the word my? why? any?) and subject to interpretation.
Otherwise, this should work for most Latinate languages.
Apropos of nothing; reminds me of one of my favorite Between the Lions performances: Sloppy Pop - Sometimes Y
Spec is 'Remove vowels from a string'; nothing about what they should be replaced with. I chose to replace them with spaces.
Strings from http://mylanguages.org/. No affiliation, but it's a nice resource. (note: these are not all the same sentence but are all from the same paragraph. They frankly were picked based on their vowel load.)
<lang perl6>my @vowels = (0x20 .. 0x2fff).map: { .chr if .chr.samemark('x') ~~ m:i/<[aæeiıoœu]>/ }
my $text = q:to/END/;
Norwegian, Icelandic, German, Turkish, French, Spanish, English: Undervisningen skal være gratis, i det minste på de elementære og grunnleggende trinn. Skal hún veitt ókeypis, að minnsta kosti barnafræðsla og undirstöðummentu. Hochschulunterricht muß allen gleichermaßen entsprechend ihren Fähigkeiten offenstehen. Öğrenim hiç olmazsa ilk ve temel safhalarında parasızdır. İlk öğretim mecburidir. L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada. Education shall be free, at least in the elementary and fundamental stages. END
put $text.subst(/@vowels/, ' ', :g);</lang>
- Output:
N rw g n, c l nd c, G rm n, T rk sh, Fr nch, Sp n sh, ngl sh: nd rv sn ng n sk l v r gr t s, d t m nst p d l m nt r g gr nnl gg nd tr nn. Sk l h n v tt k yp s, ð m nnst k st b rn fr ðsl g nd rst ð mm nt . H chsch l nt rr cht m ß ll n gl ch rm ß n ntspr ch nd hr n F h gk t n ff nst h n. ğr n m h ç lm zs lk v t m l s fh l r nd p r s zd r. lk ğr t m m cb r d r. L' d c t n d t tr gr t t , m ns n c q c nc rn l' ns gn m nt l m nt r t f nd m nt l. L nstr cc n l m nt l s r bl g t r . L nstr cc n t cn c y pr f s n l h br d s r g n r l z d . d c t n sh ll b fr , t l st n th l m nt ry nd f nd m nt l st g s.
REXX
These two REXX versions remove the Latin (Roman) vowels and all those accented and Greek vowels that are supported in the 437 code page.
using the TRANSLATE BIF
This REXX version uses the translate BIF which works faster for longer strings as there is no character-by-character manipulation. <lang rexx>/*REXX program removes vowels (both lowercase and uppercase and accented) from a string.*/ parse arg x /*obtain optional argument from the CL.*/ if x= | x="," then x= 'REXX Programming Language' /*Not specified? Then use default*/ say ' input string: ' x vowels= 'AEIOUaeiou' || "üéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜáíóúªºαΩ" /*Latin + accented + Greek*/ $= translate( xrange(), ., ' ') /*define a string of almost all chars. */ q= substr($, verify($, x), 1) /*find a character NOT in the X string.*/ y= translate(x, q, " ") /*trans. blanks in the string (for now)*/ y= space(translate(y, , vowels), 0) /*trans. vowels──►blanks, elide blanks.*/ y= translate(y, , q) /*trans the Q characters back to blanks*/ say 'output string: ' y /*stick a fork in it, we're all done. */</lang>
- output when using the default input:
input string: REXX Programming Language output string: RXX Prgrmmng Lngg
using character eliding
This REXX version uses a character-by-character manipulation and should be easier to understand. <lang rexx>/*REXX program removes vowels (both lowercase and uppercase and accented) from a string.*/ parse arg x /*obtain optional argument from the CL.*/ if x= | x="," then x= 'REXX Programming Language' /*Not specified? Then use default*/ say ' input string: ' x vowels= 'AEIOUaeiou' || "üéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜáíóúªºαΩ" /*Latin + accented + Greek*/ x= . || x /*prefix string with a dummy character.*/
do j=length(x)-1 by -1 for length(x)-1 /*process the string from the back─end.*/ _= pos( substr(x, j, 1), vowels) /*is this particular character a vowel?*/ if _==0 then iterate /*if zero (not a vowel), then skip it.*/ x= left(x, j - 1) || substr(x, j + 1) /*elide the vowel just detected from X.*/ end /*j*/
x= substr(x, 2) /*elide the prefixed dummy character. */ say 'output string: ' x /*stick a fork in it, we're all done. */</lang>
- output is identical to the 1st REXX version.
Ring
<lang ring> load "stdlib.ring" str = "Ring Programming Language" see "Input : " + str + nl for n = 1 to len(str)
if isVowel(str[n]) str = substr(str,str[n],"") ok
next see "String without vowels: " + str + nl </lang>
- Output:
Input : Ring Programming Language String without vowels: Rng Prgrmmng Lngg
Visual Basic .NET
<lang vbnet>Imports System.Text
Module Module1
Function RemoveVowels(s As String) As String Dim sb As New StringBuilder For Each c In s Select Case c Case "A", "a" Case "E", "e" Case "I", "i" Case "O", "o" Case "U", "u" Exit Select Case Else sb.Append(c) End Select Next Return sb.ToString End Function
Sub Test(s As String) Console.WriteLine("Input : {0}", s) Console.WriteLine("Output : {0}", RemoveVowels(s)) End Sub
Sub Main() Test("Visual Basic .NET") End Sub
End Module</lang>
- Output:
Input : Visual Basic .NET Output : Vsl Bsc .NT
Wren
<lang ecmascript>var removeVowels = Fn.new { |s| s.where { |c| !"aeiouAEIOU".contains(c) }.join() }
var s = "Wren Programming Language" System.print("Input : %(s)") System.print("Output : %(removeVowels.call(s))")</lang>
- Output:
Input : Wren Programming Language Output : Wrn Prgrmmng Lngg
XPL0
<lang XPL0>string 0; \make strings zero-terminated
func Disemvowel(S); \remove vowels from string char S; int I, O; [O:= 0; for I:= 0 to -1>>1 do \for many times...
[case S(I) ! $20 of \shift to lowercase ^a,^e,^i,^o,^u: [] \do nothing other [S(O):= S(I); O:= O+1]; \otherwise copy char if S(I)=0 then return S; ];
];
Text(0, Disemvowel("pack my box with FIVE DOZEN LIQUOR JUGS!"))</lang>
Output:
pck my bx wth FV DZN LQR JGS!