Monthly Archive

Categories

Count occurrence of characters in a string

How do you count occurrence of characters in a string?

 

Group-object is a ready made cmdlet to answer this question

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

$teststring.ToCharArray() |
Group-Object -NoElement |
Sort-Object -Property Count -Descending

}

 

Split the string into a character array. Pipe into group-object using –NoElement to drop the data and sort the results in descending order.

 

PS> measure-occurrence -teststring 'cwfhgfhcdsgfchgfegfegfkvcnfdhvjewy\dfsa'

Count Name
----- ----
8 f
5 g
4 c
4 h
3 d
3 e
2 w
2 s
2 v
1 k
1 n
1 j
1 y
1 \
1 a

Comments are closed.