header image

Counting vowels

Posted by: | December 28, 2018 Comments Off on Counting vowels |

If you’re given a string how would you go about counting vowels, consonants and non-alphabet characters.

 

My approach would be:

 

function measure-vowel {
[CmdletBinding()]
param (
[string]$teststring
)

$counts = [ordered]@{
Vowels = 0
Consonants = 0
NonAlphabet = 0
}

$vowels = 97, 101, 105, 111, 117

$teststring.ToLower().ToCharArray() |
foreach {
$test = [byte]$psitem

switch ($test) {
{$test -in $vowels} {$counts.Vowels += 1; break}
{$test -ge 97 -and $test -le 122} {$counts.Consonants += 1; break}
default {$counts.NonAlphabet += 1; break}
}

}

New-Object -TypeName PSObject -Property $counts

}

 

The string to test is an input parameter. Set up the output hash table and the byte value of the vowels.

 

Convert the string to lowercase and then to a char array which is put on the pipeline. Convert the char to a byte value and then use the switch statement to determine if its a vowel, consonant or non-alphabetic character.

 

Finally output the results.

under: PowerShell

Comments are closed.

Categories