Created
January 17, 2020 13:08
-
-
Save OlafD/36028166e46bb0055203f311480aadef to your computer and use it in GitHub Desktop.
Find the index of the n-th occurence of a pattern (or a single character) in a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Find the n-th occurence of a pattern in a string | |
#> | |
function IndexOfNth | |
{ | |
param ( | |
[string]$String, | |
[string]$Pattern, | |
[int]$Occurence | |
) | |
$previousPos = 0 | |
$pos = -1 | |
for ($i = 1; $i -le $Occurence; $i++) | |
{ | |
$previousPos = $pos + 1 | |
$pos = $String.IndexOf($Pattern, $previousPos) | |
} | |
return $pos | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment