Functions/Get-CommonPrefix.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function Get-CommonPrefix {
    <#
        .SYNOPSIS
            Find the common prefix of two strings.
        .DESCRIPTION
            This function will get the common prefix of two strings; that is, all
            the letters that they share, starting from the beginning of the strings.
        .EXAMPLE
            Get-CommonPrefix 'Card' 'Cartoon'
            Will get the common prefix of both string. Should output 'car'.
        .LINK
            https://communary.wordpress.com/
            https://github.com/gravejester/Communary.PASM
        .INPUTS
            System.String
        .OUTPUTS
            System.String
        .NOTES
            Author: Øyvind Kallstad
            Date: 03.11.2014
            Version 1.1
            Dependencies: none
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$String1,

        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [string]$String2,

        # Maximum length of the returned prefix.
        [Parameter()]
        [int]$MaxPrefixLength,

        # Makes matches case-sensitive. By default, matches are not case-sensitive.
        [Parameter()]
        [switch] $CaseSensitive
    )

    if (-not($CaseSensitive)) {
        $String1 = $String1.ToLowerInvariant()
        $String2 = $String2.ToLowerInvariant()
    }

    $outputString = New-Object 'System.Text.StringBuilder'
    $shortestStringLength = [Math]::Min($String1.Length,$String2.Length)

    # Let the maximum prefix length be the same as the length of the shortest of
    # the two input strings, unless defined by the MaxPrefixLength parameter.
    if (($shortestStringLength -lt $MaxPrefixLength) -or ($MaxPrefixLength -eq 0)) {
        $MaxPrefixLength = $shortestStringLength
    }

    # Loop from the start and add any characters found that are equal
    for ($i = 0; $i -lt $MaxPrefixLength; $i++) {
        if ($String1[$i] -ceq $String2[$i]) {
            [void]$outputString.Append($String1[$i])
        }
        else { break }
    }

    Write-Output $outputString.ToString()
}