Count how many vowels and consonants occur in a string: Difference between revisions

no edit summary
(→‎{{header|Python}}: Updated output)
No edit summary
 
(45 intermediate revisions by 27 users not shown)
Line 7:
<br><br>
 
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F isvowel(c)
‘ true if c is an English vowel (ignore y) ’
R c C (‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’)
 
F isletter(c)
‘ true if in English standard alphabet ’
R c C (‘a’..‘z’, ‘A’..‘Z’)
 
F isconsonant(c)
‘ true if an English consonant ’
R !isvowel(c) & isletter(c)
 
F vccounts(s)
‘ case insensitive vowel counts, total and unique ’
V a = Array(s.lowercase())
V au = Set(a)
R (sum( a.map(c -> Int(isvowel(c)))), sum( a.map(c -> Int(isconsonant(c)))),
sum(au.map(c -> Int(isvowel(c)))), sum(au.map(c -> Int(isconsonant(c)))))
 
V s = ‘Now is the time for all good men to come to the aid of their country.’
V (vcnt, ccnt, vu, cu) = vccounts(s)
print(‘String: ’s"\n Vowels: "vcnt‘ (distinct ’vu")\n Consonants: "ccnt‘ (distinct ’cu‘)’)</syntaxhighlight>
 
{{out}}
<pre>
String: Now is the time for all good men to come to the aid of their country.
Vowels: 22 (distinct 5)
Consonants: 31 (distinct 13)
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC CountVovelsConsonants(CHAR ARRAY s BYTE POINTER vov,con)
BYTE i
CHAR c
 
vov^=0 con^=0
FOR i=1 TO s(0)
DO
c=s(i)
IF c>='A AND c<='Z THEN
c==+'a-'A
FI
IF c>='a AND c<='z THEN
IF c='a OR c='e OR c='i OR c='o OR c='u THEN
vov^==+1
ELSE
con^==+1
FI
FI
OD
RETURN
 
PROC Test(CHAR ARRAY s)
BYTE vov,con
 
PrintE("Input string:")
PrintE(s)
CountVovelsConsonants(s,@vov,@con)
PrintF("Vovel count=%I, consonant count=%I%E%E",vov,con)
RETURN
 
PROC Main()
Test("Now is the time for all good men to come to the aid of their country.")
Test("Forever Action! programming language")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Count_how_many_vowels_and_consonants_occur_in_a_string.png Screenshot from Atari 8-bit computer]
<pre>
Input string:
Now is the time for all good men to come to the aid of their country.
Vovel count=22, consonant count=31
 
Input string:
Forever Action! programming language
Vovel count=13, consonant count=19
</pre>
 
=={{header|Ada}}==
This solution uses Ada 2012 aspect clauses to define discontinuous subtypes
<syntaxhighlight lang="ada">--
<lang Ada>--
-- count vowels and consonants in a string
--
Line 44 ⟶ 124:
("contains" & vowel_count'Image & " vowels and" & consonant_count'Image &
" consonants.");
end count_vowels_and_consonants;</langsyntaxhighlight>
{{out}}
<pre>
Line 54 ⟶ 134:
=={{header|ALGOL 68}}==
Showing total and distinct vowel/consonant counts, as in the Go, Wren etc. samples.
<langsyntaxhighlight lang="algol68">BEGIN # count the vowels and consonants in a string #
# returns the 0-based index of the upper case letter c in the alphabet #
# or -1 if c is not a letter #
Line 84 ⟶ 164:
print vc counts( "Now is the time for all good men to come to the aid of their country" );
print vc counts( "Help avoid turns" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 94 ⟶ 174:
5 vowels and 9 consonants (total)
</pre>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 DIM V(255),C(255)
110 FOR I = 0 TO 3
120 FOR V = 1 TO 5
130 V( ASC ( MID$ ("AEIOU",V,1)) + VAL ( MID$ ("000032128160",I * 3 + 1,3))) = 1
140 NEXT V,I
150 FOR I = 0 TO 3
160 FOR C = 1 TO 26
170 C( VAL ( MID$ ("064096192224",I * 3 + 1,3)) + C) = NOT V(64 + C)
180 NEXT C,I
190 DEF FN L(C) = C(C) OR V(C)
200 S$ = "This is 1 string" + CHR$ (13)
210 GOSUB 290
220 S$ = "This is a second string" + CHR$ (13)
230 GOSUB 290
240 PRINT "a: "V( ASC ("a"))
250 PRINT "b: "V( ASC ("b"))
260 PRINT "Z: "C( ASC ("Z"))
270 PRINT "1: " FN L( ASC ("1"))
280 END
290 GOSUB 340"VOWELS"
300 PRINT N", ";
310 GOSUB 410"CONSONANTS"
320 PRINT N", "L", "S$
330 RETURN
340 N = 0
350 L = LEN (S$)
360 IF NOT L THEN RETURN
370 FOR I = 1 TO L
380 N = N + V( ASC ( MID$ (S$,I,1)))
390 NEXT I
400 RETURN
410 N = 0
420 L = LEN (S$)
430 IF NOT L THEN RETURN
440 FOR I = 1 TO L
450 N = N + C( ASC ( MID$ (S$,I,1)))
460 NEXT I
470 RETURN</syntaxhighlight>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">vRe: {/[aeiou]/}
cRe: {/[bcdfghjklmnpqrstvwxyz]/}
 
str: lower "Now is the time for all good men to come to the aid of their country."
 
vowels: match str vRe
consonants: match str cRe
 
print ["Found" size vowels "vowels -" size unique vowels "unique"]
print ["Found" size consonants "consonants -" size unique consonants "unique"]</syntaxhighlight>
 
{{out}}
 
<pre>Found 22 vowels - 5 unique
Found 31 consonants - 13 unique</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">str := "Now is the time for all good men to come to the aid of their country."
oV:= [], oC := [], v := c := o := 0
for i, ch in StrSplit(str)
if (ch ~= "i)[AEIOU]")
v++, oV[ch] := (oV[ch]?oV[ch]:0) + 1
else if (ch ~= "i)[A-Z]")
c++, oC[ch] := (oC[ch]?oC[ch]:0) + 1
else
o++
 
Vowels := "{"
for ch, count in oV
Vowels .= """" ch """:" count ", "
Vowels := Trim(Vowels , ", ") "}"
Consonants := "{"
for ch, count in oC
Consonants .= """" ch """:" count ", "
Consonants := Trim(Consonants , ", ") "}"
 
MsgBox % result := str "`n`n" v+c+o " characters, " v " vowels, " c " consonants and " o " other"
. "`n" Vowels "`n" Consonants</syntaxhighlight>
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
69 characters, 22 vowels, 31 consonants and 16 other
{"a":2, "e":6, "i":4, "o":9, "u":1}
{"c":2, "d":2, "f":2, "g":1, "h":3, "l":2, "m":3, "N":3, "r":3, "s":1, "t":7, "w":1, "y":1}</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f COUNT_HOW_MANY_VOWELS_AND_CONSONANTS_OCCUR_IN_A_STRING.AWK
BEGIN {
str = "Now is the time for all good men to come to the aid of their country."
printf("%s\n",str)
str = toupper(str)
for (i=1; i<=length(str); i++) {
if (substr(str,i,1) ~ /[AEIOU]/) {
count_vowels++
}
else if (substr(str,i,1) ~ /[BCDFGHJKLMNPQRSTVWXYZ]/) {
count_consonants++
}
else {
count_other++
}
}
printf("%d characters, %d vowels, %d consonants, %d other\n",length(str),count_vowels,count_consonants,count_other)
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Now is the time for all good men to come to the aid of their country.
69 characters, 22 vowels, 31 consonants, 16 other
</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let ucase(c) =
'a' <= c <= 'z' -> c - 32,
c
 
let letter(c) = 'A' <= ucase(c) <= 'Z'
 
let vowel(c) =
ucase(c) = 'A' |
ucase(c) = 'E' |
ucase(c) = 'I' |
ucase(c) = 'O' |
ucase(c) = 'U'
 
let consonant(c) = letter(c) & ~vowel(c)
 
let count(p, s) = valof
$( let total = 0
for i = 1 to s%0
if p(s%i) then total := total + 1
resultis total
$)
 
let example(s) be
$( let v = count(vowel,s)
let c = count(consonant,s)
writef("'%S': %N vowels, %N consonants.*N", s, v, c)
$)
 
let start() be
example("If not now, then when? If not us, then who?")</syntaxhighlight>
{{out}}
<pre>'If not now, then when? If not us, then who?': 10 vowels, 20 consonants.</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">/*
 
https://rosettacode.org/wiki/Count_how_many_vowels_and_consonants_occur_in_a_string
 
*/
 
#include <stdio.h>
 
char vowels[] = {'a','e','i','o','u','\n'};
 
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
 
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
 
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
 
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
 
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
 
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
 
int main() {
 
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
 
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
 
 
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
</syntaxhighlight>
{{out}}
<pre>
3, 9, 16, This is 1 string
 
6, 13, 23, This is a second string
 
a: 1
b: 0
Z: 1
1: 0
 
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">ucase = proc (c: char) returns (char)
if c>='a' & c<='z' then return(char$i2c(char$c2i(c)-32))
else return(c)
end
end ucase
 
letter = proc (c: char) returns (bool)
c := ucase(c)
return(c >= 'A' & c <= 'Z')
end letter
 
vowel = proc (c: char) returns (bool)
return(string$indexc(ucase(c), "AEIOU") ~= 0)
end vowel
 
consonant = proc (c: char) returns (bool)
return(letter(c) & ~vowel(c))
end consonant
 
vowels_and_consonants = proc (s: string) returns (int,int)
vs: int := 0
cs: int := 0
for c: char in string$chars(s) do
if vowel(c) then vs := vs+1
elseif consonant(c) then cs := cs+1
end
end
return(vs,cs)
end vowels_and_consonants
 
example = proc (s: string)
po: stream := stream$primary_output()
v, c: int := vowels_and_consonants(s)
stream$putl(po, "\"" || s || "\": " || int$unparse(v)
|| " vowels, " || int$unparse(c)
|| " consonants.")
end example
 
start_up = proc ()
example("If not now, then when? If not us, then who?")
end start_up</syntaxhighlight>
{{out}}
<pre>"If not now, then when? If not us, then who?": 10 vowels, 20 consonants.</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. VOWELS-AND-CONSONANTS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CONSTANTS.
03 LETTERS-DAT.
05 FILLER PIC X(5) VALUE "AEIOU".
05 FILLER PIC X(5) VALUE "aeiou".
05 FILLER PIC X(21) VALUE "BCDFGHJKLMNPQRSTVWXYZ".
05 FILLER PIC X(21) VALUE "bcdfghjklmnpqrstvwxyz".
03 LETTERS REDEFINES LETTERS-DAT.
05 VOWELS PIC X OCCURS 10 TIMES INDEXED BY V.
05 CONSONANTS PIC X OCCURS 42 TIMES INDEXED BY C.
01 VARIABLES.
03 IN-STR PIC X(80).
03 N-VOWELS PIC 99.
03 N-CONSONANTS PIC 99.
01 REPORT.
03 R-VOWELS PIC Z9.
03 FILLER PIC X(9) VALUE " vowels, ".
03 R-CONSONANTS PIC Z9.
03 FILLER PIC X(12) VALUE " consonants.".
PROCEDURE DIVISION.
BEGIN.
MOVE "If not now, then when? If not us, then who?"
TO IN-STR.
PERFORM COUNT-AND-SHOW.
STOP RUN.
COUNT-AND-SHOW.
DISPLAY IN-STR.
PERFORM COUNT-VOWELS-AND-CONSONANTS.
MOVE N-VOWELS TO R-VOWELS.
MOVE N-CONSONANTS TO R-CONSONANTS.
DISPLAY REPORT.
COUNT-VOWELS-AND-CONSONANTS.
MOVE ZERO TO N-VOWELS, N-CONSONANTS.
SET V TO 1.
PERFORM COUNT-VOWEL 10 TIMES.
SET C TO 1.
PERFORM COUNT-CONSONANT 42 TIMES.
COUNT-VOWEL.
INSPECT IN-STR TALLYING N-VOWELS FOR ALL VOWELS(V).
SET V UP BY 1.
COUNT-CONSONANT.
INSPECT IN-STR TALLYING N-CONSONANTS FOR ALL CONSONANTS(C).
SET C UP BY 1.</syntaxhighlight>
{{out}}
<pre>If not now, then when? If not us, then who?
10 vowels, 20 consonants.</pre>
 
=={{header|Common Lisp}}==
 
<syntaxhighlight lang="lisp">(defun vowel-p (c &optional (vowels "aeiou"))
(and (characterp c) (characterp (find c vowels :test #'char-equal))))
 
(defun count-vowels (s)
(and (stringp s) (count-if #'vowel-p s)))
 
(defun count-consonants (s)
(and (stringp s) (- (count-if #'alpha-char-p s) (count-vowels s))))</syntaxhighlight>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub vowels_consonants(s: [uint8]): (vowels: intptr, consonants: intptr) is
vowels := 0;
consonants := 0;
while [s] != 0 loop
var ch := [s] | 32;
if ch >= 'a' and ch <= 'z' then
if ch == 'a' or ch == 'e' or ch == 'i'
or ch == 'o' or ch == 'u' then
vowels := vowels + 1;
else
consonants := consonants + 1;
end if;
end if;
s := @next s;
end loop;
end sub;
 
sub example(s: [uint8]) is
var vowels: intptr;
var consonants: intptr;
(vowels, consonants) := vowels_consonants(s);
print("'");
print(s);
print("': ");
print_i32(vowels as uint32);
print(" vowels, ");
print_i32(consonants as uint32);
print(" consonants.");
print_nl();
end sub;
 
example("If not now, then when? If not us, then who?");</syntaxhighlight>
{{out}}
<pre>'If not now, then when? If not us, then who?': 10 vowels, 20 consonants.</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|StdCtrls,SysUtils}}
Makes extensive use of "sets" to find vowels and consonants and determine if they are unique.
 
<syntaxhighlight lang="Delphi">
const TestStr1: string = 'Delphi is delightful.';
const TestStr2: string = 'Now is the time for all good men to come to the aid of their country.';
 
 
type TCharSet = set of 'a'..'z';
 
procedure VowelConsonant(S: string; Memo: TMemo);
{Find number of total and unique vowels and consonants}
const Vows: TCharSet = ['a','e','i','o','u'];
const Cons: TCharSet = ['a'..'z']-['a','e','i','o','u'];
var VowSet,ConSet: TCharSet;
var VCnt,CCnt,UVCnt,UCCnt,I: integer;
 
procedure HandleMatch(C: char; var Cnt,UCnt: integer; var CSet: TCharSet);
{Handle set matching and incrementing operations}
begin
Inc(Cnt);
if not (C in CSet) then Inc(UCnt);
Include(CSet,C);
end;
 
begin
Memo.Lines.Add(S);
VCnt:=0; CCnt:=0;
UVCnt:=0;UCCnt:=0;
S:=LowerCase(S);
for I:=1 to Length(S) do
begin
{Test if character is vowel or consonant}
if S[I] in Vows then HandleMatch(S[I],VCnt,UVCnt,VowSet)
else if S[I] in Cons then HandleMatch(S[I],CCnt,UCCnt,ConSet);
end;
 
Memo.Lines.Add('Vowels: '+IntToStr(VCnt));
Memo.Lines.Add('Consonants: '+IntToStr(CCnt));
Memo.Lines.Add('Unique Vowels: '+IntToStr(UVCnt));
Memo.Lines.Add('Unique Consonants: '+IntToStr(UCCnt));
end;
 
 
procedure DoVowelConsonantTest(Memo: TMemo);
{Test two strings for vowels/consonants}
begin
VowelConsonant(TestStr1,Memo);
Memo.Lines.Add('');
VowelConsonant(TestStr2,Memo);
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
Delphi is delightful.
Vowels: 6
Consonants: 12
Unique Vowels: 3
Unique Consonants: 8
 
Now is the time for all good men to come to the aid of their country.
Vowels: 22
Consonants: 31
Unique Vowels: 5
Unique Consonants: 13
 
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
proc count s$ . .
for c$ in strchars s$
c = strcode c$
if c >= 97 and c <= 122
c -= 32
.
if c >= 65 and c <= 91
c$ = strchar c
if c$ = "A" or c$ = "E" or c$ = "I" or c$ = "O" or c$ = "U"
vow += 1
else
cons += 1
.
.
.
print "There are " & vow & " vowels and " & cons & " consonants"
.
count "Now is the time for all good men to come to the aid of their country."
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Count how many vowels and consonants occur in a string. Nigel Galloway: August 1th., 202
type cType = Vowel |Consonant |Other
Line 102 ⟶ 670:
let n="Now is the time for all good men to come to the aid of their country."|>Seq.countBy(System.Char.ToLower>>fN)
printfn "%A" n
</syntaxhighlight>
</lang>
{{out}}
<pre>
seq [(Consonant, 31); (Vowel, 22); (Other, 16)]
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: ascii combinators io kernel math.statistics prettyprint
sequences ;
 
Line 121 ⟶ 690:
"Forever Factor programming language"
"Now is the time for all good men to come to the aid of their country."
[ dup ... " -> " write [ letter-type ] histogram-by . nl ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 129 ⟶ 698:
"Now is the time for all good men to come to the aid of their country."
-> H{ { "other" 16 } { "consonant" 31 } { "vowel" 22 } }
</pre>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Dim As String cadena = """Forever the FreeBASIC programming language"""
Dim As Integer vocal = 0, consonante = 0
 
Function isVowel (Byval n As String) As Boolean
Select Case Asc(n)
Case 97, 65, 101, 69, 105, 73, 111, 79, 117, 85 'aAeEiIoOuU
Return True
Case Else
Return False
End Select
End Function
 
Function isConsonant (Byval c As String) As Boolean
Dim As Boolean bool1, bool2, bool3
bool1 = Not isvowel(c)
bool2 = (Asc(c) > 64 And Asc(c) < 91)
bool3 = (Asc(c) > 96 And Asc(c) < 123)
If bool1 And (bool2 Or bool3) Then
Return True
Else
Return False
End If
End Function
 
For n As Integer = 1 To Len(cadena)
Dim As String letra = Mid(cadena,n,1)
If isVowel(letra) Then vocal += 1
If isConsonant(letra) Then consonante += 1
Next n
 
Print "Input string = "; cadena
Print "In string occur"; vocal; " vowels"
Print "In string occur"; consonante; " consonants"
Sleep</syntaxhighlight>
{{out}}
<pre>
Input string = "Forever the FreeBASIC programming language"
In string occur 15 vowels
In string occur 23 consonants
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
 
void local fn StringGetVowelAndConsonantCount( string as CFStringRef, vowels as ^long, consonents as ^long )
CFCharacterSetRef vowelSet = fn CharacterSetWithCharactersInString( @"aeiou" )
CFMutableCharacterSetRef consonantSet = fn MutableCharacterSetLetterSet
fn MutableCharacterSetRemoveCharactersInString( consonantSet, @"aeiou" )
*vowels = len( fn StringComponentsSeparatedByCharactersInSet( string, vowelSet ) ) - 1
*consonents = len( fn StringComponentsSeparatedByCharactersInSet( string, consonantSet ) ) - 1
end fn
 
void local fn DoIt
long index, vowels, consonants
CFArrayRef strings = @[@"abcdefghijklmnop345qrstuvwxyz",
@"The quick brown fox jumps over the lazy dog",
@"The answer my friend is blowin' in the wind"]
for index = 0 to len(strings) - 1
fn StringGetVowelAndConsonantCount( strings[index], @vowels, @consonants )
NSLog(@"\"%@\" contains %ld vowels and %ld consonants",strings[index],vowels,consonants)
next
end fn
 
fn Doit
 
HandleEvents</syntaxhighlight>
{{out}}
<pre>
"abcdefghijklmnop345qrstuvwxyz" contains 5 vowels and 21 consonants
"The quick brown fox jumps over the lazy dog" contains 11 vowels and 24 consonants
"The answer my friend is blowin' in the wind" contains 11 vowels and 23 consonants
</pre>
 
=={{header|Go}}==
Same approach as the Wren entry.
<langsyntaxhighlight lang="go">package main
 
import (
Line 167 ⟶ 814:
fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap))
}
}</langsyntaxhighlight>
 
{{out}}
Line 185 ⟶ 832:
One of (at least) four possible meanings here:
 
<langsyntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bifunctor (bimap, first, second)
import Data.Bool (bool)
Line 236 ⟶ 883:
if p
then t
else f</langsyntaxhighlight>
{{Out}}
<pre>Unique vowels and consonants used, with counts:
Line 246 ⟶ 893:
Another of (at least) four possible meanings:
 
<langsyntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.Char (isAlpha)
import Data.List (intercalate, partition)
import qualified Data.Map.Strict as M
 
Line 271 ⟶ 918:
 
isVowel :: Char -> Bool
isVowel c = c (`elem` "aeiouAEIOU")
 
--------------------------- TEST -------------------------
Line 291 ⟶ 938:
<> fmap
('\t' :)
( [ show vTotalconcatMap
<> " characters drawn from "report
[ ("vowels", <> show (lengthvTotal, v),
<> (" vowels:consonants", cTotal, c)
]
<> (('\t' :) . show <$> v)
<> [ "",
show cTotal <> " characters drawn from "
<> show (length c)
<> " consonants:"
]
<> (('\t' :) . show <$> c)
)
 
------------------------ FORMATTING ----------------------
 
report :: (String, Int, [(Char, Int)]) -> [String]
report (label, total, xs) =
[ show total
<> ( " characters drawn from "
<> show (length xs)
<> (' ' : label)
<> ":"
)
]
<> (('\t' :) . show <$> xs)
<> [""]
 
------------------------- GENERIC ------------------------
 
both :: (a -> b) -> (a, a) -> (b, b)
both = join bimap</langsyntaxhighlight>
{{Out}}
<pre>33 'vowels and consonants'
Line 329 ⟶ 983:
('t',1)
('v',1)</pre>
 
=={{header|J}}==
 
For this task, we restrict ourselves to english letters, and treat the semivowels (<code>w</code> and <code>y</code>) as consonants.
 
Implementation (two tallies: vowels first, consonants second):
 
<syntaxhighlight lang="j">vowel=: (,toupper) 'aeiou'
consonant=: (,toupper) (a.{~97+i.16) -. vowel
vctally=: e.&vowel ,&(+/) e.&consonant</syntaxhighlight>
 
Examples:
 
<syntaxhighlight lang="j"> vctally 'Now is the time for all good men to come to the aid of their country.'
22 18
vctally 'Forever Action! programming language'
13 13</syntaxhighlight>
 
An alternative expression for <code>consonant</code> could be:
 
<syntaxhighlight lang="j">consonant=: (a.#~2|'@Z`z'I.a.) -. vowel</syntaxhighlight>
 
=={{header|JavaScript}}==
This is a new genre of deliberately ambiguous task description, perhaps ?
 
I suppose it might be thought to offer scope for variety,
but is it really consistent with the core Rosetta goal of comparability ?
 
(There seem to have been a surprising number of these recently, often
associated with tasks of uncertain novelty ...)
 
===Count of "Vowels and Consonants" ?===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// -------- COUNT OF "VOWELS AND CONSONANTS" ---------
 
// countOfVowelsAndConsonants :: String -> Int
const countOfVowelsAndConsonants = s =>
Array.from(s).filter(isAlpha).length;
 
 
// ---------------------- TEST -----------------------
const main = () =>
`${countOfVowelsAndConsonants(
"Forever Fortran 2018 programming language"
)} "vowels and consonants"`;
 
 
// --------------------- GENERIC ---------------------
 
// isAlpha :: Char -> Bool
const isAlpha = c =>
(/[A-Za-z\u00C0-\u00FF]/u).test(c);
 
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>33 "vowels and consonants"</pre>
 
===Counts of distinct vowels and distinct consonants seen ?===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// NUMBERS OF DISTINCT VOWELS, AND DISTINCT CONSONANTS
 
// distinctVowelsAndConsonants ::
// String -> ([Char], [Char])
const distinctVowelsAndConsonants = s =>
both(
cs => sort(Array.from(new Set(cs)))
)(
partition(isVowel)(
Array.from(s).filter(isAlpha)
)
);
 
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const vc = both(
cs => `(${cs.join("")}, ${cs.length})`
)(
distinctVowelsAndConsonants(
"Forever Fortran 2018 programming language"
)
);
 
return [
`Distinct vowels: ${vc[0]}`,
`Distict consonants: ${vc[1]}`
].join("\n\n");
};
 
// --------------------- GENERIC ---------------------
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2
});
 
 
// both :: (a -> b) -> (a, a) -> (b, b)
const both = f =>
ab => Tuple(
f(ab[0])
)(
f(ab[1])
);
 
 
// isAlpha :: Char -> Bool
const isAlpha = c =>
(/[A-Za-z\u00C0-\u00FF]/u).test(c);
 
 
// isVowel :: Char -> Bool
const isVowel = c =>
(/[AEIOUaeiou]/u).test(c);
 
 
// partition :: (a -> Bool) -> [a] -> ([a], [a])
const partition = p =>
// A tuple of two lists - those elements in
// xs which match p, and those which do not.
xs => xs.reduce(
(a, x) => p(x) ? (
Tuple(a[0].concat(x))(a[1])
) : Tuple(a[0])(a[1].concat(x)),
Tuple([])([])
);
 
// sort :: Ord a => [a] -> [a]
const sort = xs =>
// An A-Z sorted copy of xs.
xs.slice()
.sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));
 
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>Distinct vowels: (aeiou, 5)
 
Distict consonants: (Fglmnprtv, 9)</pre>
 
===Counts of vowel and consonant occurrences ?===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// ---- COUNTS OF VOWEL AND CONSONANT OCCURRENCES ----
 
// vowelConsonantOccurrenceTotals :: String -> (Int, Int)
const vowelConsonantOccurrenceTotals = s =>
Array.from(s).reduce(
(ab, c) => (
isAlpha(c) ? (
isVowel(c) ? (
first(succ)
) : second(succ)
) : identity
)(ab),
Tuple(0)(0)
);
 
// ---------------------- TEST -----------------------
const main = () => {
const vc =
vowelConsonantOccurrenceTotals(
"Forever Fortran 2018 programming language"
);
 
return [
`Vowel occurrences: ${vc[0]}`,
`Consonent occurrences: ${vc[1]}`
].join("\n\n");
};
 
 
// --------------------- GENERIC ---------------------
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2
});
 
// first :: (a -> b) -> ((a, c) -> (b, c))
const first = f =>
// A simple function lifted to one which applies
// to a tuple, transforming only its first item.
xy => {
const tpl = Tuple(f(xy[0]))(xy[1]);
 
return Array.isArray(xy) ? (
Array.from(tpl)
) : tpl;
};
 
// identity :: a -> a
const identity = x =>
// The identity function.
x;
 
// isAlpha :: Char -> Bool
const isAlpha = c =>
(/[A-Za-z\u00C0-\u00FF]/u).test(c);
 
// isVowel :: Char -> Bool
const isVowel = c =>
(/[AEIOUaeiou]/u).test(c);
 
// second :: (a -> b) -> ((c, a) -> (c, b))
const second = f =>
// A function over a simple value lifted
// to a function over a tuple.
// f (a, b) -> (a, f(b))
xy => {
const tpl = Tuple(xy[0])(f(xy[1]));
 
return Array.isArray(xy) ? (
Array.from(tpl)
) : tpl;
};
 
// succ :: Int -> Int
const succ = x =>
1 + x;
 
return main();
})();</syntaxhighlight>
{{Out}}
<pre>Vowel occurrences: 12
 
Consonent occurrences: 21</pre>
 
===Counts of occurrence for each vowel and consonant ?===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// COUNTS OF OCCURRENCE FOR EACH VOWEL AND CONSONANT
 
// countsOfEachVowelAndConsonant ::
// String -> ([(Char, Int)], [(Char, Int)])
const countsOfEachVowelAndConsonant = s =>
partition(
cn => isVowel(cn[0])
)(
sort(
Object.entries(
charCounts(
Array.from(s).filter(isAlpha)
)
)
)
.map(([c, n]) => Tuple(c)(n))
);
 
// ---------------------- TEST -----------------------
const main = () => {
const report = label =>
cns => {
const
total = cns.reduce(
(a, cn) => a + cn[1],
0
),
rows = cns.map(
compose(s => `\t${s}`, showTuple)
).join("\n");
 
return [
`${label} counts:\n${rows}`,
`\ttotal: ${total}`
].join("\n\n");
};
 
const counts = countsOfEachVowelAndConsonant(
"Forever Fortran 2018 programming language"
);
 
return Array.from(
bimap(
report("Vowel")
)(
report("Consonant")
)(
counts
)
).join("\n\n");
};
 
 
// --------------------- GENERIC ---------------------
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2
});
 
 
// bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
const bimap = f =>
// Tuple instance of bimap.
// A tuple of the application of f and g to the
// first and second values respectively.
g => tpl => Tuple(f(tpl[0]))(
g(tpl[1])
);
 
 
// charCounts :: String -> Dict
const charCounts = s => {
// A dictionary of characters seen,
// with their frequencies.
const go = (dct, c) =>
Object.assign(dct, {
[c]: 1 + (dct[c] || 0)
});
 
return Array.from(s).reduce(go, {});
};
 
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
 
 
// isAlpha :: Char -> Bool
const isAlpha = c =>
(/[A-Za-z\u00C0-\u00FF]/u).test(c);
 
 
// isVowel :: Char -> Bool
const isVowel = c =>
(/[AEIOUaeiou]/u).test(c);
 
 
// partition :: (a -> Bool) -> [a] -> ([a], [a])
const partition = p =>
// A tuple of two lists - those elements in
// xs which match p, and those which do not.
xs => xs.reduce(
(a, x) => p(x) ? (
Tuple(a[0].concat(x))(a[1])
) : Tuple(a[0])(a[1].concat(x)),
Tuple([])([])
);
 
 
// sort :: Ord a => [a] -> [a]
const sort = xs =>
// An A-Z sorted copy of xs.
xs.slice()
.sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));
 
 
// showTuple :: Tuple -> String
const showTuple = tpl =>
`(${tpl[0]}, ${tpl[1]})`;
 
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>Vowel counts:
(a, 4)
(e, 3)
(i, 1)
(o, 3)
(u, 1)
 
total: 12
 
Consonant counts:
(F, 2)
(g, 4)
(l, 1)
(m, 2)
(n, 3)
(p, 1)
(r, 6)
(t, 1)
(v, 1)
 
total: 21</pre>
 
=={{header|jq}}==
Line 335 ⟶ 1,396:
 
This entry focuses solely on the A-Z alphabet.
<syntaxhighlight lang="jq">
<lang jq>
def is_lowercase_vowel: IN("a","e","i","o","u");
def is_lowercase_letter: "a" <= . and . <= "z";
Line 360 ⟶ 1,421:
| pp, "";
 
task</langsyntaxhighlight>
{{out}}
<pre>
Line 381 ⟶ 1,442:
}
</pre>
 
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">isvowel(c) = c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
isletter(c) = 'a' <= c <= 'z' || 'A' <= c <= 'Z'
isconsonant(c) = !isvowel(c) && isletter(c)
Line 404 ⟶ 1,466:
 
testvccount()
</langsyntaxhighlight>{{out}}
<pre>
String: Forever Julia programming language
Line 414 ⟶ 1,476:
Consonants: 31 (distinct 13)
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Count how many vowels and consonants occur in a string
 
# # Variables:
#
string1="Now is the time for all good men to come to the aid of their country."
string=${1:-${string1}} # Allow command line input
 
consonant="b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|w|x|y|z"
vowel="a|e|i|o|u"
 
integer i rc
typeset -ia lettercnt uniquecnt
typeset -a letlist
 
# # Functions:
#
# # Function _vorc(ch) - Return 0 if consonant; 1 if vowel; 99 else
#
function _vorc {
typeset _ch ; typeset -l _char="$1"
 
[[ "${_char}" == @(${consonant}) ]] && return 0
[[ "${_char}" == @(${vowel}) ]] && return 1
return 99
}
 
# # Function _uniq(char, type, list, arr) - increment arr[] if chart not in list[]
#
function _uniq {
typeset _char ; _char="$1"
typeset _type ; integer _type=$2
typeset _list ; nameref _list="$3"
typeset _arr ; nameref _arr="$4"
 
if [[ "${_char}" != @(${_list[_type]% *}) ]]; then
_list[_type]+="${_char}|" # Add letter to the proper list
(( _arr[_type]++ )) # Increment uniq counter
fi
}
 
######
# main #
######
 
echo "${string}" | while read ; do
for ((i=0; i<${#REPLY}; i++)); do
char="${REPLY:${i}:1}"
_vorc "${char}" ; rc=$?
(( rc != 99 )) && (( lettercnt[rc]++ )) && _uniq "${char}" ${rc} letlist uniquecnt
done
done
 
printf "\n%s\n\n" "${string}"
printf "Consonants: %3d (Unique: %2d)\n" "${lettercnt[0]}" "${uniquecnt[0]}"
printf " Vowlels: %3d (Unique: %2d)\n" "${lettercnt[1]}" "${uniquecnt[1]}"
</syntaxhighlight>{{out}}
<pre>
Now is the time for all good men to come to the aid of their country.
 
Consonants: 31 (Unique: 13)
Vowlels: 22 (Unique: 5)</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">vowels = {"a", "e", "i", "o", "u"};
conso = {"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"};
vowels = Join[vowels, ToUpperCase@vowels];
conso = Join[conso, ToUpperCase@conso];
str = "The universe is under no obligation to make sense to you.";
<|"vowels" -> StringCount[str, Alternatives @@ vowels],
"consonants" -> StringCount[str, Alternatives @@ conso],
"other" -> StringCount[str, Except[Alternatives @@ Join[vowels, conso]]]|></syntaxhighlight>
{{out}}
<pre><|"vowels" -> 22, "consonants" -> 24, "other" -> 11|></pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE VowelsAndConsonants;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
 
PROCEDURE uppercase(c: CHAR): CHAR;
BEGIN
IF (c >= 'a') AND (c <= 'z') THEN
c := CHR(ORD(c) - 32);
END;
RETURN c;
END uppercase;
 
PROCEDURE CountVowelsAndConsonants(s: ARRAY OF CHAR; VAR v, c: CARDINAL);
VAR i, length: CARDINAL;
ch: CHAR;
BEGIN
v := 0;
c := 0;
length := Length(s);
IF length > 0 THEN
FOR i := 0 TO length-1 DO
ch := uppercase(s[i]);
IF (ch >= 'A') AND (ch <= 'Z') THEN
IF (ch = 'A')
OR (ch = 'E')
OR (ch = 'I')
OR (ch = 'O')
OR (ch = 'U') THEN
INC(v);
ELSE
INC(c);
END;
END;
END;
END;
END CountVowelsAndConsonants;
 
PROCEDURE Display(s: ARRAY OF CHAR);
VAR v, c: CARDINAL;
BEGIN
WriteString('"');
WriteString(s);
WriteString('": ');
CountVowelsAndConsonants(s, v, c);
WriteCard(v, 0);
WriteString(' vowels, ');
WriteCard(c, 0);
WriteString(' consonants.');
WriteLn;
END Display;
 
BEGIN
Display("If not now, then when? If not us, then who?");
END VowelsAndConsonants.</syntaxhighlight>
{{out}}
<pre>"If not now, then when? If not us, then who?": 10 vowels, 20 consonants.</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strutils
 
const
Line 441 ⟶ 1,639:
value(consonantCount, "consonant"))
 
vcCount("Now is the time for all good men to come to the aid of their country.")</langsyntaxhighlight>
 
{{out}}
Line 447 ⟶ 1,645:
5 vowels and 13 consonants (distinct)
22 vowels and 31 consonants (total)</pre>
 
=={{header|Pascal}}==
Standard “Unextended” Pascal (ISO standard 7185) does not really know the notion of strings:
<syntaxhighlight lang="pascal">program countHowManyVowelsAndConsonantsOccurInAString(input, output);
 
var
vowel, consonant: set of char;
vowelCount, consonantCount: integer;
 
begin
{ initialize variables - - - - - - - - - - - - - - - - - - }
vowel := ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'];
consonant := ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y',
'Z', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];
vowelCount := 0;
consonantCount := 0;
{ process - - - - - - - - - - - - - - - - - - - - - - - - - }
while not EOF do
begin
{ input^ refers to the buffer variable's value }
vowelCount := vowelCount + ord(input^ in vowel);
consonantCount := consonantCount + ord(input^ in consonant);
get(input)
end;
{ result - - - - - - - - - - - - - - - - - - - - - - - - - }
writeLn(vowelCount, ' vowels');
writeLn(consonantCount, ' consonants')
end.</syntaxhighlight>
{{in}}
The quick brown fox jumps over the lazy dog.
{{out}}
11 vowels
24 consonants
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Count_how_many_vowels_and_consonants_occur_in_a_string
Line 464 ⟶ 1,700:
TEST ONE
Now is the time for all good men to come to the aid of their country.
Forever Perl Programming Language</langsyntaxhighlight>
{{out}}
<pre>
Line 479 ⟶ 1,715:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">count_vowels_and_consonants</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 491 ⟶ 1,727:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">count_vowels_and_consonants</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
The string "Now is the time for all good men to come to the aid of their country."
contains 22 vowels (5 distinct), 31 consonants (13 distinct), and 16 other (2 distinct).
</pre>
 
=={{header|Picat}}==
===List comprehension===
Also using maps for counting individual characters.
<syntaxhighlight lang="picat">main =>
S = "Count how many vowels and consonants occur in a string",
vowels(Vowels),
consonants(Consonants),
CountVowels = [C : C in S, membchk(C,Vowels)].len,
CountConsonants = [C : C in S, membchk(C,Consonants)].len,
println([vowels=CountVowels,consonants=CountConsonants,rest=(S.len-CountVowels-CountConsonants)]),
nl,
 
% Occurrences of each character
println(all=count_chars(S)),
println(vowels=count_chars(S,Vowels)),
println(consonants=count_chars(S,Consonants)),
nl.
 
vowels("aeiouAEIOU").
consonants("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ").
 
count_chars(S) = count_chars(S,"").
count_chars(S,Cs) = Map =>
Map = new_map(),
foreach(C in S, (Cs != "" -> membchk(C,Cs) ; true))
Map.put(C,Map.get(C,0)+1)
end.</syntaxhighlight>
 
{{out}}
<pre>[vowels = 15,consonants = 30,rest = 9]
 
all = (map)[m = 1,s = 4,w = 2,C = 1,e = 1,c = 3,h = 1,n = 8,u = 2,t = 3,a = 4,d = 1,i = 2,l = 1,o = 6,r = 2,v = 1,y = 1, = 9,g = 1]
vowels = (map)[u = 2,i = 2,o = 6,a = 4,e = 1]
consonants = (map)[m = 1,s = 4,w = 2,C = 1,c = 3,h = 1,n = 8,t = 3,d = 1,l = 1,r = 2,v = 1,y = 1,g = 1]</pre>
 
===Recursion===
<syntaxhighlight lang="picat">main =>
S = "Count how many vowels and consonants occur in a string",
vowels(Vowels),
consonants(Consonants),
NumVowels = count_set(Vowels,S),
NumConsonants = count_set(Consonants,S),
NumRest = S.len - NumVowels - NumConsonants,
println([vowels=NumVowels,consontants=NumConsonants,rest=NumRest]),
nl.
vowels("aeiouAEIOU").
consonants("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ").
 
count_set(Set,S) = Vs =>
count_set(Set,S,0,Vs).
count_set(_Set,[],Vs,Vs).
count_set(Set,[C|Cs],Vs0,Vs) :-
(membchk(C,Set) ->
Vs1 = Vs0 + 1
;
Vs1 = Vs0
),
count_set(Set,Cs,Vs1,Vs).</syntaxhighlight>
 
{{out}}
<pre>[vowels = 15,consontants = 30,rest = 9]</pre>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Put "Now is the time for all good men to come to the aid of their country." into a string.
Find a vowel count and a consonant count of the string.
Write the double-quote byte then the string then the double-quote byte on the console.
Write "Number of vowels: " then the vowel count on the console.
Write "Number of consonants: " then the consonant count on the console.
Wait for the escape key.
Shut down.
 
To find a vowel count and a consonant count of a string:
Slap a substring on the string.
Loop.
If the substring is blank, exit.
Put the substring's first's target into a letter.
If the letter is any vowel, bump the vowel count.
If the letter is any consonant, bump the consonant count.
Add 1 to the substring's first.
Repeat.</syntaxhighlight>
 
{{out}}
<pre>
"Now is the time for all good men to come to the aid of their country."
Number of vowels: 22
Number of consonants: 31
</pre>
 
=={{header|Python}}==
{{trans|Julia}}
<langsyntaxhighlight lang="python">def isvowel(c):
""" true if c is an English vowel (ignore y) """
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
Line 528 ⟶ 1,856:
 
testvccount()
</langsyntaxhighlight>{{out}}<pre>
String: Forever Python programming language
Vowels: 11 (distinct 5)
Line 540 ⟶ 1,868:
 
Or, selecting another of the various possible meanings of an ambiguous task description:
<langsyntaxhighlight lang="python">'''Total and individual counts of vowel and consonant instances'''
 
from functools import reduce
Line 636 ⟶ 1,964:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>33 "vowels and consonants"
Line 657 ⟶ 1,985:
('t', 1)
('v', 1)</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ bit
[ 0 $ "AEIOUaeiuo"
witheach [ bit | ] ] constant
& 0 != ] is vowel ( c --> b )
 
[ bit
[ 0 $ "BCDFGHJKLMNPQRSTVWXYZ"
$ "bcdfghjklmnpqrstvwxyz" join
witheach [ bit | ] ] constant
& 0 != ] is consonant ( c --> b )
 
[ 0 0 rot witheach
[ tuck vowel +
dip [ consonant + ] ] ] is task ( $ --> n n )
$ "How fleeting are all human passions compared"
$ " with the massive continuity of ducks." join
task
echo say " vowels" cr
echo say " consonants"</syntaxhighlight>
 
{{out}}
 
<pre>26 vowels
43 consonants
</pre>
 
'''OR''', depending on how you interpret the task…
 
<syntaxhighlight lang="quackery"> [ 0 $ "AEIOU"
witheach [ bit | ] ] constant is vowels ( --> n )
 
[ 0 $ "BCDFGHJKLMNPQRSTVWXYZ"
witheach [ bit | ] ] constant is consonants ( --> n )
 
[ 0 swap
[ dup 0 > while
tuck 1 & +
swap 1 >> again ]
drop ] is bitcount ( n --> n )
 
[ 0 swap witheach [ upper bit | ]
dup consonants & bitcount
swap vowels & bitcount ] is task ( $ --> n n )
 
$ "How fleeting are all human passions compared"
$ " with the massive continuity of ducks." join
task
echo say " distinct vowels" cr
echo say " distinct consonants"</syntaxhighlight>
 
{{out}}
 
<pre>5 distinct vowels
16 distinct consonants
</pre>
 
=={{header|Raku}}==
Note that the task '''does not''' ask for the '''total count''' of vowels and consonants, but for '''how many''' occur.
 
<syntaxhighlight lang="raku" perl6line>my @vowels = <a e i o u>;
my @consonants = <b c d f g h j k l m n p q r s t v w x y z>;
 
Line 669 ⟶ 2,060:
}
 
say letter-check "Forever Ring Programming Language";</langsyntaxhighlight>
 
{{out}}
<pre>5 vowels and 8 consonants occur in the string "Forever Ring Programming Language"</pre>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
REBOL [
Title: "Count how many vowels and consonants occur in a string"
Date: 21-Dec-2022
Author: "Earldridge Jazzed Pineda"
]
 
countVowelsConsonants: func [string] [
vowels: [#"a" #"e" #"i" #"o" #"u"]
consonants: [#"b" #"c" #"d" #"f" #"g" #"h" #"j" #"k" #"l" #"m" #"n" #"p" #"q" #"r" #"s" #"t" #"v" #"w" #"x" #"y" #"z"]
 
vowelCount: 0
consonantCount: 0
 
foreach character string [
if (find consonants character) <> none [consonantCount: consonantCount + 1]
if (find vowels character) <> none [vowelCount: vowelCount + 1]
]
 
return reduce [vowelCount consonantCount]
]
 
string: "Count how many vowels and consonants occur in a string"
counts: countVowelsConsonants string
print [mold string "has" pick counts 1 "vowels and" pick counts 2 "consonants"]
</syntaxhighlight>
{{out}}
<pre>{Count how many vowels and consonants occur in a string} has 15 vowels and 30 consonants</pre>
 
=={{header|REXX}}==
=== version 1 ===
<langsyntaxhighlight lang="rexx">/* REXX */
Parse Arg s
If s='' Then
Line 698 ⟶ 2,120:
sv=translate(s,copies('+',length(vow))copies(' ',256),vow||xrange('00'x,'ff'x))
Say length(space(sc,0)) tag 'consonants,' length(space(sv,0)) tag 'vowels'
Return</langsyntaxhighlight>
{{out}}
<pre>Forever Wren programming language
Line 705 ⟶ 2,127:
 
=== version 2 ===
<langsyntaxhighlight lang="rexx">/*REXX program counts the vowels and consonants (unique and total) in a given string. */
parse arg $ /*obtain optional argument from the CL.*/
if $='' then $= 'Now is the time for all good men to come to the aid of their country.'
Line 717 ⟶ 2,139:
/*──────────────────────────────────────────────────────────────────────────────────────*/
cnt: arg k; do j=1 to length(@.k); if pos(substr(@.k,j,1),$)>0 then #.k=#.k+1; end; return
init: @.1='AEIOU'; @.2="BCDFGHJKLMNPQRSTVWXYZ"; upper $; $=space($,0); L=length($); return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 726 ⟶ 2,148:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">? "working..."
<lang ring>
load "stdlib.ring"
see "working..." + nl
str = '"' + "Forever Ring Programming Language" + '"'
vowel = 0 vowels = [] for x in "AEIOUaeiou" add(vowels, x) next
vowel = 0
ltrc = 0 all = 'A':'z' while all[27] != 'a' del(all, 27) end
cons =0
 
for n =in 1 to len(str)
if find(vowels, n) > 0 vowel++ ok
strc = str[n]
if isvowelfind(str[all, n]) => 0 ltrc++ 1ok
vowel += 1
ok
if isconsonant(strc)
cons += 1
ok
next
 
see? "Input string = " + str + nl
see? "In string occur " + vowel + " vowels" + nl
see? "In string occur " + cons(ltrc - vowel) + " consonants" + nl
seeput "done..." + nl</syntaxhighlight>
 
func isconsonant(c)
bool1 = not isvowel(c)
bool2 = (ascii(c) > 64 and ascii(c) < 91)
bool3 = (ascii(c) > 96 and ascii(c) < 123)
if bool1 and (bool2 or bool3)
return 1
else
return 0
ok
</lang>
{{out}}
<pre>working...
working...
Input string = "Forever Ring Programming Language"
In string occur 11 vowels
In string occur 19 consonants
done...</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.8}}
≪ "AEIOU" → str voy
≪ (0,0) 1 str SIZE '''FOR''' j
str j DUP SUB
'''IF''' DUP "a" ≥ OVER "z" ≤ AND '''THEN''' NUM 32 - CHR '''END'''
'''IF''' DUP "A" ≥ OVER "Z" ≤ AND '''THEN''' voy SWAP POS 1 (0,1) IFTE + '''ELSE''' DROP '''END'''
'''NEXT'''
≫ ≫ ''''VOYCON'''' STO
 
"Now is the time for all good men to come to the aid of their country." '''VOYCON'''
{{out}}
<pre>
1: (22,31)
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">RE_V = /[aeiou]/
RE_C = /[bcdfghjklmnpqrstvwxyz]/
str = "Now is the time for all good men to come to the aid of their country."
Line 781 ⟶ 2,199:
 
grouped.each{|k,v| puts "#{k}: #{v.size}, #{v.uniq.size} unique."}
</syntaxhighlight>
</lang>
{{out}}
<pre>Consonants: 31, 13 unique.
Line 787 ⟶ 2,205:
Other: 16, 2 unique.
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::io ;
 
//string supposed to contain ascii letters only!
fn main() {
println!("Enter a string!");
let mut inline : String = String::new( ) ;
io::stdin( ).read_line( &mut inline ).unwrap( ) ;
let entered_line : &str = &*inline ;
let vowels = vec!['a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' ,
'O' , 'U'] ;
let numvowels = entered_line.trim( ).chars( ).filter( | c |
vowels.contains( c ) ).count( ) ;
let consonants = entered_line.trim( ).chars( ).filter( | c |
! vowels.contains( c ) && c.is_ascii_alphabetic( )).count( ) ;
println!("String {:?} contains {} vowels and {} consonants!" ,
entered_line.trim( ) , numvowels , consonants ) ;
}</syntaxhighlight>
{{out}}
<pre>
Enter a string!
Rust shares properties of procedural and functional languages!
String "Rust shares properties of procedural and functional languages!" contains 21 vowels and 33 consonants!
</pre>
 
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
* Program: countvc.sbl,
* To run: sbl countvc.sbl
* Description: Count how many vowels and consonants occur in a string
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
 
 
* Function SQUEEZE will remove some characters from s (string).
* Parameter c is the character set to keep or remove.
* If parameter kr is 1, then only characters in c will be kept.
* If it is 0, then the characters in c will be removed.
* Parameter kr defaults to 1. So if it is null or not 0 or 1,
* then it becomes 1.
define('squeeze(s,c,kr)pre')
:(squeeze_end)
squeeze
kr = (eq(size(kr),0) 1,kr)
kr = (eq(kr,1) kr, eq(kr,0) kr, 1)
eq(kr,1) :s(kr1)
kr0
* Exclude character set
s ? breakx(c) . pre span(c) = :f(kr2)
squeeze = squeeze pre
:(kr0)
kr1
* Include character set
s ? breakx(c) span(c) . pre = :f(kr2)
squeeze = squeeze pre
:(kr1)
kr2
:(return)
squeeze_end
 
 
* Function POPT will populate table t with counts
* for each, unique character from string.
* It first standarizes string to only contain
* upper and lower case letters and then replaces
* upper case letters with lower case letters.
* It returns t converted to an array.
define('popt(string,t)s,c') :(popt_end)
popt
s = squeeze(string,&lcase &ucase)
s = replace(s,&ucase,&lcase)
popt1
s ? len(1) . c = ?(t[c] = t[c] + 1) :s(popt1)
popt = convert(t,'ARRAY') :s(return)f(freturn)
popt_end
 
 
* Function OUTPUTARRAY will output array as well as return the number
* of unique array elements and the sum of their counts,
* separated by the |.
define('outputarray(a)i,sum,n') :(outputarray_end)
outputarray
i = i + 1
output = a[i,1] ', ' a[i,2] :f(outputarray2)
sum = sum + a[i,2]
n = i
:(outputarray)
outputarray2
outputarray = n "|" sum
:(return)
outputarray_end
 
 
alphabet = &lcase &ucase
vowels = 'aeiouAEIOU'
consonants = squeeze(alphabet,vowels,0) ;* Remove vowels
 
v = table()
c = table()
 
s = "Now is the time for all good men to come to the aid of their country."
 
output = s
 
vs = squeeze(s,vowels,1) ;* Remove all characters if not a vowel
va = popt(vs,v) ;* Put unique characters into array with counts
ret = outputarray(va) ;* Output character array
ret ? breakx("|") . n len(1) rem . sum
output = "Number of unique vowels is " n ', total=' sum
 
cs = squeeze(s,consonants,1) ;* Remove all characters if not a consonant
vc = popt(cs,c) ;* Put unique characters into array with counts
ret = outputarray(vc) ;* Output character array
ret ? breakx("|") . n len(1) rem . sum
output = "Number of unique consonants is " n ', total=' sum
 
END
</syntaxhighlight>
{{out}}
<pre>
Now is the time for all good men to come to the aid of their country.
o, 9
i, 4
e, 6
a, 2
u, 1
Number of unique vowels is 5, total=22
n, 3
w, 1
s, 1
t, 7
h, 3
m, 3
f, 2
r, 3
l, 2
g, 1
d, 2
c, 2
y, 1
Number of unique consonants is 13, total=31
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-str}}
In the absence of any indications to the contrary, we take a simplistic view of only considering English ASCII vowels (not 'y') and consonants.
<langsyntaxhighlight ecmascriptlang="wren">import "./str" for Str
 
var vowels = "aeiou"
Line 818 ⟶ 2,380:
System.print("contains (total) %(vc) vowels and %(cc) consonants.")
System.print("contains (distinct) %(vmap.count) vowels and %(cmap.count) consonants.\n")
}</langsyntaxhighlight>
 
{{out}}
Line 833 ⟶ 2,395:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<langsyntaxhighlight lang="asm"> .model tiny
.code
.486
Line 963 ⟶ 2,525:
msg4 db " consonants."
crlf db 0Dh, 0Ah, 0
end start</langsyntaxhighlight>
 
{{out}}
Line 977 ⟶ 2,539:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0; \use zero-terminated strings
int VTC, VDC, \vowel total count, vowel distinct count
CTC, CDC, \consonant total count, consonant distinct count
Line 1,012 ⟶ 2,574:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
258

edits