PowerShell for Windows Admins

Dec 6 2018   9:12AM GMT

Count the occurrence of given character in a string

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: