Saturday, April 12, 2014

PowerShell : count occurrences of specific character in a string

Recently I wanted to count the occurrences of specific character in a string.

As an example, let’s say we want to count number of  ‘/’ characters in a given url . Following is a sample PowerShell to get the result.

  1. $url = "http://sp13/sites/1/2/3"
  2. $charCount = ($url.ToCharArray() | Where-Object {$_ -eq '/'} | Measure-Object).Count
  3. Write-Host $charCount

8 comments:

Unknown said...

Thanks!

aodennison said...

Another way:
$newString = $oldString -replace "x", ""
$count = $oldString.Length - $newString.Length

Unknown said...

Much better and faster way

($url.Split('/')).count-1

NostraDavid said...

($url.ToCharArray() -eq '"').count

Even clearer! :D

Anonymous said...

Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. this

Unknown said...

Here is a nice one if you want to count each of the char in a string.

$url = "http://sp13/sites/1/2/3")
$url.ToCharArray() | group

Count Name Group
----- ---- -----
1 h {h}
3 t {t, t, t}
2 p {p, p}
1 : {:}
6 / {/, /, /, /...}
3 s {s, s, s}
2 1 {1, 1}
2 3 {3, 3}
1 i {i}
1 e {e}
1 2 {2}

Unknown said...

($url.Split('/')).count-1

Is not correct, as it counts the split elements and not the number of appearances of the character we are looking for. Might be nit-picking, but still. Code right.


($url.ToCharArray() -eq '"').count

This is but correct, we get the number of the characters we are looking for.

Unknown said...

Just as a tip, you might have to cast the object to a string or convert it to a string using .ToString before doing .ToCharArray