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.
- $url = "http://sp13/sites/1/2/3"
- $charCount = ($url.ToCharArray() | Where-Object {$_ -eq '/'} | Measure-Object).Count
- Write-Host $charCount
8 comments:
Thanks!
Another way:
$newString = $oldString -replace "x", ""
$count = $oldString.Length - $newString.Length
Much better and faster way
($url.Split('/')).count-1
($url.ToCharArray() -eq '"').count
Even clearer! :D
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
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}
($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.
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
Post a Comment