Monthly Archive

Categories

Monthly Archives: December 2018

Count the occurrence of given character in a string

Last time I showed how to get the number of occurrences of each character in a string but how do you count the occurrence of given character in a string?

 

You use one of the fundamental concepts on which PowerShell is built – its composability. In other words PowerShell is composed of a lot of very small pieces of code that each do its own job and you select and assemble the components you need to complete a given task.

 

What that boils down to is that you already have a function that counts the number of occurrences of a character in a string. Rather than writing another function, or spending time modifying your existing function, see if you use other PowerShell cmdlets (or functions) help you get the result you need. In this case:

 

PS> measure-occurrence -teststring 'cwfhgfhcdsgfchgfegfegfkvcnfdhvjewy\dfsa' | where Name -eq 's'

Count Name
----- ----
2 s

 

Gives you the result you want without any further work.

 

Two ways to use the function makes it more cost effective to write.

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