Skip to content

Instantly share code, notes, and snippets.

@OlafD
Created January 17, 2020 13:08
Show Gist options
  • Save OlafD/36028166e46bb0055203f311480aadef to your computer and use it in GitHub Desktop.
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.
<#
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