Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a "Longest Common Substring" function for two strings in PowerShell (based on wikibooks <a href="http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#C.23" rel="nofollow">C# example</a>):</p> <pre><code>Function get-LongestCommonSubstring { Param( [string]$String1, [string]$String2 ) if((!$String1) -or (!$String2)){Break} # .Net Two dimensional Array: $Num = New-Object 'object[,]' $String1.Length, $String2.Length [int]$maxlen = 0 [int]$lastSubsBegin = 0 $sequenceBuilder = New-Object -TypeName "System.Text.StringBuilder" for ([int]$i = 0; $i -lt $String1.Length; $i++) { for ([int]$j = 0; $j -lt $String2.Length; $j++) { if ($String1[$i] -ne $String2[$j]) { $Num[$i, $j] = 0 }else{ if (($i -eq 0) -or ($j -eq 0)) { $Num[$i, $j] = 1 }else{ $Num[$i, $j] = 1 + $Num[($i - 1), ($j - 1)] } if ($Num[$i, $j] -gt $maxlen) { $maxlen = $Num[$i, $j] [int]$thisSubsBegin = $i - $Num[$i, $j] + 1 if($lastSubsBegin -eq $thisSubsBegin) {#if the current LCS is the same as the last time this block ran [void]$sequenceBuilder.Append($String1[$i]); }else{ #this block resets the string builder if a different LCS is found $lastSubsBegin = $thisSubsBegin $sequenceBuilder.Length = 0 #clear it [void]$sequenceBuilder.Append($String1.Substring($lastSubsBegin, (($i + 1) - $lastSubsBegin))) } } } } } return $sequenceBuilder.ToString() } </code></pre> <p><strong>To use this for more than two strings, use it like this:</strong></p> <pre><code>Function get-LongestCommonSubstringArray { Param( [Parameter(Position=0, Mandatory=$True)][Array]$Array ) $PreviousSubString = $Null $LongestCommonSubstring = $Null foreach($SubString in $Array) { if($LongestCommonSubstring) { $LongestCommonSubstring = get-LongestCommonSubstring $SubString $LongestCommonSubstring write-verbose "Consequtive diff: $LongestCommonSubstring" }else{ if($PreviousSubString) { $LongestCommonSubstring = get-LongestCommonSubstring $SubString $PreviousSubString write-verbose "first one diff: $LongestCommonSubstring" }else{ $PreviousSubString = $SubString write-verbose "No PreviousSubstring yet, setting it to: $PreviousSubString" } } } Return $LongestCommonSubstring } get-LongestCommonSubstringArray $Arr -verbose </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload