Monthly Archive

Categories

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.

Comments are closed.