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

no edit summary
(Add Cowgol)
No edit summary
 
(27 intermediate revisions by 19 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!}}==
<langsyntaxhighlight Actionlang="action!">PROC CountVovelsConsonants(CHAR ARRAY s BYTE POINTER vov,con)
BYTE i
CHAR c
Line 42 ⟶ 75:
Test("Now is the time for all good men to come to the aid of their country.")
Test("Forever Action! programming language")
RETURN</langsyntaxhighlight>
{{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]
Line 57 ⟶ 90:
=={{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 91 ⟶ 124:
("contains" & vowel_count'Image & " vowels and" & consonant_count'Image &
" consonants.");
end count_vowels_and_consonants;</langsyntaxhighlight>
{{out}}
<pre>
Line 101 ⟶ 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 131 ⟶ 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 141 ⟶ 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">
<lang AWK>
# syntax: GAWK -f COUNT_HOW_MANY_VOWELS_AND_CONSONANTS_OCCUR_IN_A_STRING.AWK
BEGIN {
Line 162 ⟶ 280:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 170 ⟶ 288:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let ucase(c) =
Line 201 ⟶ 319:
 
let start() be
example("If not now, then when? If not us, then who?")</langsyntaxhighlight>
{{out}}
<pre>'If not now, then when? If not us, then who?': 10 vowels, 20 consonants.</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">/*
<lang C>/*
 
https://rosettacode.org/wiki/Count_how_many_vowels_and_consonants_occur_in_a_string
Line 282 ⟶ 400:
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 295 ⟶ 413:
 
</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}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub vowels_consonants(s: [uint8]): (vowels: intptr, consonants: intptr) is
Line 332 ⟶ 565:
end sub;
 
example("If not now, then when? If not us, then who?");</langsyntaxhighlight>
{{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 343 ⟶ 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>
Line 351 ⟶ 678:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: ascii combinators io kernel math.statistics prettyprint
sequences ;
 
Line 363 ⟶ 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 375 ⟶ 702:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Dim As String cadena = """Forever the FreeBASIC programming language"""
Dim As Integer vocal = 0, consonante = 0
Line 409 ⟶ 736:
Print "In string occur"; vocal; " vowels"
Print "In string occur"; consonante; " consonants"
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 417 ⟶ 744:
</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 454 ⟶ 814:
fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap))
}
}</langsyntaxhighlight>
 
{{out}}
Line 472 ⟶ 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 523 ⟶ 883:
if p
then t
else f</langsyntaxhighlight>
{{Out}}
<pre>Unique vowels and consonants used, with counts:
Line 533 ⟶ 893:
Another of (at least) four possible meanings:
 
<langsyntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.Char (isAlpha)
Line 602 ⟶ 962:
 
both :: (a -> b) -> (a, a) -> (b, b)
both = join bimap</langsyntaxhighlight>
{{Out}}
<pre>33 'vowels and consonants'
Line 623 ⟶ 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}}==
Line 634 ⟶ 1,015:
 
===Count of "Vowels and Consonants" ?===
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 660 ⟶ 1,041:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>33 "vowels and consonants"</pre>
 
===Counts of distinct vowels and distinct consonants seen ?===
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 749 ⟶ 1,130:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Distinct vowels: (aeiou, 5)
Line 756 ⟶ 1,137:
 
===Counts of vowel and consonant occurrences ?===
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 842 ⟶ 1,223:
 
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Vowel occurrences: 12
Line 849 ⟶ 1,230:
 
===Counts of occurrence for each vowel and consonant ?===
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 986 ⟶ 1,367:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Vowel counts:
Line 1,015 ⟶ 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 1,040 ⟶ 1,421:
| pp, "";
 
task</langsyntaxhighlight>
{{out}}
<pre>
Line 1,064 ⟶ 1,445:
 
=={{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 1,085 ⟶ 1,466:
 
testvccount()
</langsyntaxhighlight>{{out}}
<pre>
String: Forever Julia programming language
Line 1,097 ⟶ 1,478:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 1,155 ⟶ 1,536:
printf "Consonants: %3d (Unique: %2d)\n" "${lettercnt[0]}" "${uniquecnt[0]}"
printf " Vowlels: %3d (Unique: %2d)\n" "${lettercnt[1]}" "${uniquecnt[1]}"
</langsyntaxhighlight>{{out}}
<pre>
Now is the time for all good men to come to the aid of their country.
Line 1,163 ⟶ 1,544:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="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];
Line 1,170 ⟶ 1,551:
<|"vowels" -> StringCount[str, Alternatives @@ vowels],
"consonants" -> StringCount[str, Alternatives @@ conso],
"other" -> StringCount[str, Except[Alternatives @@ Join[vowels, conso]]]|></langsyntaxhighlight>
{{out}}
<pre><|"vowels" -> 22, "consonants" -> 24, "other" -> 11|></pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE VowelsAndConsonants;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
Line 1,228 ⟶ 1,609:
BEGIN
Display("If not now, then when? If not us, then who?");
END VowelsAndConsonants.</langsyntaxhighlight>
{{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 1,258 ⟶ 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 1,264 ⟶ 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 1,281 ⟶ 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 1,296 ⟶ 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 1,308 ⟶ 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 1,345 ⟶ 1,856:
 
testvccount()
</langsyntaxhighlight>{{out}}<pre>
String: Forever Python programming language
Vowels: 11 (distinct 5)
Line 1,357 ⟶ 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 1,453 ⟶ 1,964:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>33 "vowels and consonants"
Line 1,477 ⟶ 1,988:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ bit
[ 0 $ "AEIOUaeiuo"
witheach [ bit | ] ] constant
Line 1,498 ⟶ 2,009:
echo say " vowels" cr
echo say " consonants"</langsyntaxhighlight>
 
{{out}}
Line 1,508 ⟶ 2,019:
'''OR''', depending on how you interpret the task…
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 $ "AEIOU"
witheach [ bit | ] ] constant is vowels ( --> n )
 
Line 1,530 ⟶ 2,041:
echo say " distinct vowels" cr
echo say " distinct consonants"</langsyntaxhighlight>
 
{{out}}
Line 1,541 ⟶ 2,052:
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 1,549 ⟶ 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 1,578 ⟶ 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 1,585 ⟶ 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 1,597 ⟶ 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 1,606 ⟶ 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 1,661 ⟶ 2,199:
 
grouped.each{|k,v| puts "#{k}: #{v.size}, #{v.uniq.size} unique."}
</syntaxhighlight>
</lang>
{{out}}
<pre>Consonants: 31, 13 unique.
Line 1,667 ⟶ 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 1,698 ⟶ 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 1,713 ⟶ 2,395:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<langsyntaxhighlight lang="asm"> .model tiny
.code
.486
Line 1,843 ⟶ 2,525:
msg4 db " consonants."
crlf db 0Dh, 0Ah, 0
end start</langsyntaxhighlight>
 
{{out}}
Line 1,857 ⟶ 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,892 ⟶ 2,574:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
258

edits