Get-NthIndexOf

It turned out that I don’t need to use this function I wrote but I’m sure there will be time when I will need it, so I’m pasting the code here. This function basically gives you the index of the character at the #th occurrence.

Function Get-NthIndexOf
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Position=0,Mandatory=$true)] 
        [string] $TargetString,
        [Parameter(Position=1,Mandatory=$true)] 
        [char] $CharToFind,
        [Parameter(Position=2,Mandatory=$true)] 
        [int] $Nth,
        [Parameter(Position=3,Mandatory=$false)] 
        [boolean] $Forward = $true
    )

    If ($Forward)
    {
        $occurence = 0
        For ([int] $i = 0; $i -lt $TargetString.Length; $i++)
        {
            If ($TargetString[$i] -eq $CharToFind)
            {
                $occurence++
                If ($Nth -eq $occurence)
                {
                    Return $i
                }
            }
        }
    }
    Else
    {
        $occurence = 0
        For ([int] $i = $TargetString.Length - 1; $i -gt 0; $i--)
        {
            If ($TargetString[$i] -eq $CharToFind)
            {
                $occurence++
                If ($Nth -eq $occurence)
                {
                    Return $i
                }
            }
        }
    }

    #Code falling here means it didn't find the char at all or $occurence just didn't reach $Nth
    Return -1

}

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *