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.

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

3 Responses to Count the occurrence of given character in a string

  1. Luke says:

    Hi Richard,

    The term ‘measure-occurrence’ is not recognized as the name of a cmdlet, function, script file, or operable program.

    Same error message on PowerShell 5.1 or 6.1.1

    Did you install a specific module?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s