Longest common substring: Difference between revisions

m
m (→‎{{header|Haskell}}: Applied Ormolu)
 
(48 intermediate revisions by 24 users not shown)
Line 21:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F longest_common_substring(s1, s2)
V ir = 0
V jr = -1
Line 36:
R s1[ir..jr]
 
print(longest_common_substring(‘thisisatest’, ‘testing123testing’))</langsyntaxhighlight>
 
{{out}}
<pre>
test
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE Func Equals(CHAR ARRAY a,b)
BYTE i
 
IF a(0)#b(0) THEN
RETURN (0)
FI
 
FOR i=1 TO a(0)
DO
IF a(i)#b(i) THEN
RETURN (0)
FI
OD
RETURN (1)
 
PROC Lcs(CHAR ARRAY a,b,res)
CHAR ARRAY t(100)
BYTE i,j,len
 
IF a(0)<b(0) THEN
len=a(0)
ELSE
len=b(0)
FI
 
WHILE len>0
DO
FOR i=1 to a(0)-len+1
DO
SCopyS(res,a,i,i+len-1)
FOR j=1 to b(0)-len+1
DO
SCopyS(t,b,j,j+len-1)
IF Equals(res,t) THEN
RETURN
FI
OD
OD
len==-1
OD
res(0)=0
RETURN
 
PROC Test(CHAR ARRAY a,b)
CHAR ARRAY res(100)
 
Lcs(a,b,res)
PrintF("lcs(""%S"",""%S"")=""%S""%E",a,b,res)
RETURN
 
PROC Main()
Test("thisisatest","testing123testing")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Longest_common_substring.png Screenshot from Atari 8-bit computer]
<pre>
lcs("thisisatest","testing123testing")="test"
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io;
 
procedure Longest_Common_Substring is
Line 73 ⟶ 133:
begin
Ada.Text_Io.Put_Line (Common ("thisisatest", "testing123testing"));
end Longest_Common_Substring;</langsyntaxhighlight>
{{out}}
<pre>
Line 80 ⟶ 140:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
test_string(text &g, text v, text l)
{
integer n;
 
n = 0prefix(v, l);
whileif (l[n] && v[n]~g ==< l[n]) {
n += 1;
}
if (length(g) < n) {
g = cut(l, 0, n);
}
}
 
longest(text u, v)
longest(text u, text v)
{
record r;
text g, l, s;
 
while (length(~u)) {
r[u] = 0;
u = delete(u, 0);
}
while (length(~v)) {
if (rsk_lower(r, v, l)) {
test_string(g, v, l);
Line 114 ⟶ 170:
}
 
return g;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="aime">o_(longest("thisisatest", "testing123testing"), "\n");</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">BEGIN
# returns the longest common substring of s and t #
PROC longest common substring = ( STRING s, t )STRING:
BEGIN
STRING s1 = s[ @ 1 ]; # normalise bounds to 1 : ... #
STRING s2 = t[ @ 1 ];
STRING result := "";
INT result len := 0;
FOR i TO UPB s1 DO
FOR j TO UPB s2 DO
IF s1[ i ] = s2[ j ] THEN
INT k := 1;
WHILE INT ik = i + k;
INT jk = j + k;
IF ik > UPB s1 OR jk > UPB s2
THEN FALSE
ELSE s1[ ik ] = s2[ jk ]
FI
DO
k +:= 1
OD;
IF k > result len THEN
# found a longer substring #
result len := k;
result := s1[ i : ( i + k ) - 1 ]
FI
FI
OD
OD;
result
END # longest common substring # ;
 
# task test case #
print( ( longest common substring( "thisisatest", "testing123testing" ), newline ) )
END</syntaxhighlight>
{{out}}
<pre>
test
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">lcs←{
sb←∪⊃,/{⌽¨,\⌽⍵}¨,\⍵
match←(sb(∨/⍷)¨⊂⍺)/sb
⊃((⌈/=⊢)≢¨match)/match
}</syntaxhighlight>
{{out}}
<syntaxhighlight lang="apl">
'testing123testing' lcs 'thisisatest'
test</syntaxhighlight>
 
=={{header|AppleScript}}==
Line 122 ⟶ 230:
This allows for the possibility of co-longest substrings, returning one instance of each. If either input string is empty, it's taken as meaning there are no common substrings.
 
<langsyntaxhighlight lang="applescript">on LCS(a, b)
-- Identify the shorter string. The longest common substring won't be longer than it!
set lengthA to a's length
Line 154 ⟶ 262:
return longestMatches
end LCS</langsyntaxhighlight>
 
<langsyntaxhighlight lang="applescript">LCS("thisisatest", "testing123testing")</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight lang="applescript">{"test"}</langsyntaxhighlight>
 
Or:
<langsyntaxhighlight lang="applescript">LCS("thisisthebesttest", "besting123testing")</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight lang="applescript">{"best", "test"}</langsyntaxhighlight>
 
===Functional===
Using library functions wherever possible, for better productivity,
(and for more granular Rosetta comparison):
<langsyntaxhighlight lang="applescript">------------------ LONGEST COMMON SUBSTRING ----------------
 
-- longestCommon :: Eq a => [a] -> [a] -> [a]
Line 349 ⟶ 457:
end script
map(residue, es) & {""}
end tails</langsyntaxhighlight>
{{Out}}
<pre>"test"</pre>
 
=={{header|Applesoft BASIC}}==
{{trans|BASIC256}}
<syntaxhighlight lang="gwbasic"> 0 A$ = "thisisatest":B$ = "testing123testing": GOSUB 100"LONGEST COMMON SUBSTRING": PRINT R$;: END
100 LET R$ = ""
110 LET A = LEN (A$)
120 LET B = LEN (B$)
130 IF A = 0 OR B = 0 THEN RETURN
140 FOR B = B TO 1 STEP - 1
150 FOR J = B TO 1 STEP - 1
160 FOR K = 1 TO A
170 IF MID$ (A$,K,J) < > LEFT$ (B$,J) THEN NEXT K
180 LET R$ = LEFT$ (B$,J)
190 IF A > K THEN RETURN
200 NEXT J
210 LET B$ = MID$ (B$,2)
220 NEXT B
230 LET R$ = ""
240 RETURN</syntaxhighlight>
{{out}}
<pre>
test
</pre>
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">lcs: function [a,b][
lengths: map 0..size a => [map 0..size b => 0]
greatestLength: 0
Line 363 ⟶ 493:
if x=y [
if? or? i=0 j=0 ->
set lengths \ [i ]\[j]: 0
else ->
set lengths \ [i ]\[j]: (1 + (lengths \ [i-1) ]\ [j-1)]
 
if greatestLength < (lengths \ [i) ]\ [j] [
greatestLength: (lengths \ [i) ]\ [j]
result: slice a (i-greatestLength)+1 i
]
Line 377 ⟶ 507:
]
 
print lcs "thisisatest", "testing123testing"</langsyntaxhighlight>
 
{{out}}
Line 385 ⟶ 515:
=={{header|AutoHotkey}}==
===Using Text Comparison===
<langsyntaxhighlight AutoHotkeylang="autohotkey">LCS(a, b){
x := i := 1
while StrLen(x)
Line 392 ⟶ 522:
res := StrLen(res) > StrLen(x) ? res : x
return res
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % LCS("thisisatest", "testing123testing")</langsyntaxhighlight>
Outputs:<pre>test</pre>
===Using RegEx===
<langsyntaxhighlight AutoHotkeylang="autohotkey">LCS(a, b){
while pos := RegExMatch(a "`n" b, "(.+)(?=.*\R.*\1)", m, pos?pos+StrLen(m):1)
res := StrLen(res) > StrLen(m1) ? res : m1
return res
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % LCS("thisisatest", "testing123testing")</langsyntaxhighlight>
Outputs:<pre>test</pre>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="bacon">FUNCTION Common_Sub$(haystack$, needle$)
 
WHILE LEN(needle$)
Line 417 ⟶ 547:
ENDFUNC
 
PRINT Common_Sub$("thisisatest", "testing123testing")</langsyntaxhighlight>
{{out}}
<pre>test</pre>
 
=={{header|BASIC}}==
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">CALL LCS("thisisatest", "testing123testing")
END
 
SUB LCS (a$, b$)
IF LEN(a$) = 0 OR LEN(b$) = 0 THEN PRINT "": EXIT SUB
WHILE LEN(b$)
FOR j = LEN(b$) TO 1 STEP -1
IF INSTR(a$, LEFT$(b$, j)) THEN PRINT LEFT$(b$, j): EXIT SUB
NEXT j
b$ = MID$(b$, 2)
WEND
END SUB</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="lb">call LCS "thisisatest", "testing123testing"
end
 
sub LCS a$, b$
if len(a$) = 0 or len(b$) = 0 then print "": exit sub
while len(b$)
for j = len(b$) to 1 step -1
if instr(a$, left$(b$, j)) then print left$(b$, j): exit sub
next j
b$ = mid$(b$, 2)
wend
end sub</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">SUB lcs (a$,b$)
IF LEN(a$) = 0 OR LEN(b$) = 0 THEN
PRINT ""
EXIT SUB
END IF
DO WHILE LEN(b$)<>0
FOR j = LEN(b$) TO 1 STEP -1
IF POS(a$,(b$)[1:j])<>0 THEN
PRINT (b$)[1:j]
EXIT SUB
END IF
NEXT j
LET b$ = (b$)[2:maxnum]
LOOP
END SUB
 
CALL lcs ("thisisatest", "testing123testing")
END</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight BASIC256lang="basic256">function LCS(a, b)
if length(a) = 0 or length(b) = 0 then return ""
while length(b)
Line 435 ⟶ 624:
 
print LCS("thisisatest", "testing123testing")
end</langsyntaxhighlight>
 
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat"> ( lcs
= X a b x L
. !arg:(?a.?b)
Line 456 ⟶ 645:
)
)
& out$(lcs$(thisisatest.testing123testing))</langsyntaxhighlight>
'''Output'''
<pre>test</pre>
Line 462 ⟶ 651:
=={{header|C}}==
{{trans|Modula-2}}
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
void lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) {
Line 503 ⟶ 692:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>test</pre>
Line 509 ⟶ 698:
=={{header|C sharp|C#}}==
===Using dynamic programming===
<langsyntaxhighlight lang="csharp">using System;
 
namespace LongestCommonSubstring
Line 548 ⟶ 737:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 556 ⟶ 745:
===Searching for smaller substrings of a in b===
{{trans|REXX}}
<langsyntaxhighlight lang="csharp">//C# program tests the LCSUBSTR (Longest Common Substring) subroutine.
using System;
namespace LongestCommonSubstring
Line 590 ⟶ 779:
}
}
}</langsyntaxhighlight>
'''output''' when using the default inputs:
<pre>
Line 600 ⟶ 789:
===Searching for smaller substrings of a in b (simplified)===
{{trans|zkl}}
<langsyntaxhighlight lang="csharp">//C# program tests the LCS (Longest Common Substring) subroutine.
using System;
namespace LongestCommonSubstring
Line 633 ⟶ 822:
}
}
</syntaxhighlight>
</lang>
'''output''' when using the default inputs:
<pre>
Line 643 ⟶ 832:
=={{header|C++}}==
{{Works with|C++14}}
<langsyntaxhighlight lang="cpp">#include <string>
#include <algorithm>
#include <iostream>
Line 692 ⟶ 881:
std::cout << "\"" << lcs( s1, s2 ) << "\" !\n";
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>The longest common substring of thisisatest and testing123testing is:
Line 699 ⟶ 888:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun longest-common-substring (a b)
"Return the longest substring common to a and b"
Line 720 ⟶ 909:
result :test #'equal )))))
result ))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 727 ⟶ 916:
 
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
sub Contains(s1: [uint8], s2: [uint8]): (r: uint8) is
r := 0;
while [s1] != 0 loop
var a := s1;
var b := s2;
while [b] != 0 and [a] == [b] loop
a := @next a;
b := @next b;
end loop;
if [b] == 0 then
r := 1;
return;
end if;
s1 := @next s1;
end loop;
end sub;
 
sub LCS(s1: [uint8], s2: [uint8], outbuf: [uint8]) is
if StrLen(s1) < StrLen(s2) then
var temp := s1;
s1 := s2;
s2 := temp;
end if;
 
var maxlen := StrLen(s2);
var length := maxlen;
while length > 0 loop
var start: intptr := 0;
while start + length <= maxlen loop
MemCopy(s2 + start, length, outbuf);
[outbuf + length + 1] := 0;
if Contains(s1, outbuf) != 0 then
return;
end if;
start := start + 1;
end loop;
length := length - 1;
end loop;
[outbuf] := 0;
end sub;
 
var lcs: uint8[64];
LCS("thisisatest", "testing123testing", &lcs[0]);
print(&lcs[0]);
print_nl();</syntaxhighlight>
{{out}}
<pre>test</pre>
=={{header|D}}==
{{trans|C#}}
<langsyntaxhighlight lang="d">import std.stdio;
 
string lcs(string a, string b) {
Line 759 ⟶ 999:
void main() {
writeln(lcs("testing123testing", "thisisatest"));
}</langsyntaxhighlight>
{{out}}
<pre>test</pre>
Line 765 ⟶ 1,005:
=={{header|Delphi}}==
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Longest_Common_Substring;
 
Line 814 ⟶ 1,054:
readln;
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 826 ⟶ 1,066:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">func lComSubStr(w1, w2) {
var (len, end) = (0, 0)
var mat = Array.emptyEmpty(w1.lenLength() + 1, () => Array.emptyEmpty(w2.lenLength() + 1, 0))
var (i, j) = (0, 0)
 
for sLett in w1 {
for tLett in w2 {
if tLett == sLett {
constlet curLen = mat[i][j] + 1
mat[i + 1][j + 1] = curLen
if curLen > len {
len = curLen
end = i
}
}
Line 846 ⟶ 1,086:
i += 1
}
String(values =: w1).subSubstring((end + 1) - len, len)
}
func comSubStr(w1, w2) {
return String(lComSubStr(w1.iterIterate().toArrayToArray(), w2.iterIterate().toArrayToArray()))
}
comSubStr("thisisatest", "testing123testing") // "test"</syntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight>
comSubStr("thisisatest", "testing123testing") // "test"</lang>
func$ lcs a$ b$ .
if a$ = "" or b$ = ""
return ""
.
while b$ <> ""
for j = len b$ downto 1
l$ = substr b$ 1 j
for k = 1 to len a$ - j + 1
if substr a$ k j = l$
if len l$ > len max$
max$ = l$
.
break 2
.
.
.
b$ = substr b$ 2 9999
.
return max$
.
print lcs "thisisatest" "testing123testing"
print lcs "thisisatest" "stesting123testing"
print lcs "thisisatestxestinoo" "xxtesting123testing"
</syntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.3}}
<langsyntaxhighlight lang="elixir">defmodule LCS do
def longest_common_substring(a,b) do
alist = to_charlist(a) |> Enum.with_index
Line 878 ⟶ 1,146:
end
 
IO.puts LCS.longest_common_substring("thisisatest", "testing123testing")</langsyntaxhighlight>
 
{{out}}
Line 887 ⟶ 1,155:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<langsyntaxhighlight lang="factor">USING: io sequences.extras ;
 
"thisisatest" "testing123testing" longest-subseq print</langsyntaxhighlight>
{{out}}
<pre>
Line 895 ⟶ 1,163:
</pre>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
program main
implicit none
call compare('testing123testingthing', 'thisis', 'thi')
call compare('testing', 'sting', 'sting')
call compare('thisisatest_stinger', 'testing123testingthing', 'sting')
call compare('thisisatest_stinger', 'thisis', 'thisis')
call compare('thisisatest', 'testing123testing', 'test')
call compare('thisisatest', 'thisisatest', 'thisisatest')
contains
subroutine compare(a,b,answer)
character(len=*),intent(in) :: a, b, answer
character(len=:),allocatable :: a2, match
character(len=*),parameter :: g='(*(g0))'
integer :: i
a2=a ! should really make a2 the shortest and b the longest
match=''
do i=1,len(a2)-1
call compare_sub(a2,b,match)
if(len(a2).lt.len(match))exit
a2=a2(:len(a2)-1)
enddo
write(*,g) merge('(PASSED)','(FAILED)',answer.eq.match), &
& ' longest match found: "',match,'"; expected "',answer,'"', &
& ' comparing "',a,'" and "',b,'"'
end subroutine
subroutine compare_sub(a,b,match)
character(len=*),intent(in) :: a, b
character(len=:),allocatable :: match
integer :: left, foundat, len_a
len_a=len(a)
do left=1,len_a
foundat=index(b,a(left:))
if(foundat.ne.0.and.len(match).lt.len_a-left+1)then
if(len(a(left:)).gt.len(match))then
match=a(left:)
exit
endif
endif
enddo
end subroutine compare_sub
end program main
</syntaxhighlight>
 
{{out}}
<pre>
(PASSED) longest match found: "thi"; expected "thi" comparing "testing123testingthing" and "thisis"
(PASSED) longest match found: "sting"; expected "sting" comparing "testing" and "sting"
(PASSED) longest match found: "sting"; expected "sting" comparing "thisisatest_stinger" and "testing123testingthing"
(PASSED) longest match found: "thisis"; expected "thisis" comparing "thisisatest_stinger" and "thisis"
(PASSED) longest match found: "test"; expected "test" comparing "thisisatest" and "testing123testing"
(PASSED) longest match found: "thisisatest"; expected "thisisatest" comparing "thisisatest" and "thisisatest"
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Function LCS(a As String, b As String) As String
If Len(a) = 0 Or Len(b) = 0 Then Return ""
While Len(b)
Line 908 ⟶ 1,230:
 
Print LCS("thisisatest", "testing123testing")
Sleep</langsyntaxhighlight>
 
 
=={{header|Go}}==
{{trans|C#}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 940 ⟶ 1,262:
func main() {
fmt.Println(lcs("thisisatest", "testing123testing"))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 947 ⟶ 1,269:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.Ord (comparing)
import Data.List (maximumBy, intersect)
 
Line 962 ⟶ 1,284:
 
main :: IO ()
main = putStrLn $ longestCommon "testing123testing" "thisisatest"</langsyntaxhighlight>
{{out}}
<pre>test</pre>
Line 968 ⟶ 1,290:
Or, fusing subStrings as ''tail . inits <=< tails''
 
<langsyntaxhighlight lang="haskell">import Control.Monad ((<=<))
import Data.List (inits, intersect, maximumBy, tails)
import Data.Ord (comparing)
Line 985 ⟶ 1,307:
main =
putStrLn $
longestCommon "testing123testing" "thisisatest"</langsyntaxhighlight>
{{Out}}
<pre>test</pre>
Line 995 ⟶ 1,317:
In other words: this can be suitable for small problems, but you might want something better if you're comparing gigabyte length strings with high commonality.
 
<langsyntaxhighlight Jlang="j">lcstr=:4 :0
C=. ({.~ 1+$) x=/y
M=. >./ (* * * >. * + (_1&|.)@:|:^:2)^:_ C
N=. >./ M
y {~ (M i. N)-i.-N
)</langsyntaxhighlight>
 
Intermedate results:
Line 1,010 ⟶ 1,332:
Example use:
 
<langsyntaxhighlight Jlang="j"> 'thisisatest' lcs 'testing123testing'
test</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class LongestCommonSubstring {
 
public static void main(String[] args) {
Line 1,041 ⟶ 1,363:
return res;
}
}</langsyntaxhighlight>
 
<pre>test</pre>
Line 1,050 ⟶ 1,372:
=={{header|JavaScript}}==
{{Trans|Haskell}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,163 ⟶ 1,485:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>test</pre>
Line 1,172 ⟶ 1,494:
 
'''Utility functions''':
<langsyntaxhighlight lang="jq"># Create an m x n matrix
def matrix(m; n; init):
if m == 0 then []
Line 1,183 ⟶ 1,505:
 
def set(i;j; value):
setpath([i,j]; value);</langsyntaxhighlight>
 
'''Longest Common Substring''':
<langsyntaxhighlight lang="jq">def lcs(a; b):
matrix(a|length; b|length; 0) as $lengths
# state: [ $lengths, greatestLength, answer ]
Line 1,205 ⟶ 1,527:
end
else .
end )) | .[2];</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">lcs("thisisatest"; "testing123testing")</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -f Longest_common_substring.jq
"test"</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.5}}
 
<langsyntaxhighlight lang="julia">function lcs(s1::AbstractString, s2::AbstractString)::String
l, r, sub_len = 1, 0, 0
for i in eachindex(s1)
sub_len = 0
for i in 1:length(s1)
for j in i:length(s1)
if !contains(s2, SubString(s1, i, j)) || break
elseifif sub_len < j - i
l, r = i, j
sub_len = j - i
Line 1,227 ⟶ 1,548:
end
end
return s1[l:r]
end
 
@show lcs("thisisatest", "testing123testing")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun lcs(a: String, b: String): String {
Line 1,251 ⟶ 1,572:
}
 
fun main(args: Array<String>) = println(lcs("testing123testing", "thisisatest"))</langsyntaxhighlight>
 
{{out}}
<pre>
test
</pre>
 
=={{header|Lambdatalk}}==
1) A pure lambdatalk version
<syntaxhighlight lang="scheme">
{def lcs
{def lcs.rec
{lambda {:a :b :w}
{if {or {< {W.length :a} 2} {< {W.length :b} 2} }
then {W.rest :w}
else {if {W.equal? {W.first :a} {W.first :b}}
then {lcs.rec {W.rest :a} {W.rest :b} :w{W.first :a}}
else {let { {:x {lcs.rec :a {W.rest :b} :w}}
{:y {lcs.rec {W.rest :a} :b :w}}
} {if {> {W.length :x} {W.length :y}}
then :x
else :y} }}}}}
{lambda {:a :b}
{lcs.rec :a# :b# #}}}
-> lcs
 
{lcs testing123testing thisisatest}
-> tsitest // 23000ms
</syntaxhighlight>
 
2) The pure lambdatalk version is very, very slow, 23000ms.
A much more easier and faster way is to build an interface with the javascript code entry, {{trans|Javascript}}, used as it is.
 
<syntaxhighlight lang="scheme">
{jslcs testing123testing thisisatest}
-> tsitest // 130ms
 
{script
// the lcs function code is in the javascript entry
 
LAMBDATALK.DICT["jslcs"] = function() {
var args = arguments[0].split(" ");
return lcs( args[0], args[1] )
};
}
</syntaxhighlight>
 
=={{header|langur}}==
{{trans|Julia}}
<syntaxhighlight lang="langur">val .lcs = fn(.s1, .s2) {
var .l, .r, .sublen = 1, 0, 0
for .i of .s1 {
for .j in .i .. len(.s1) {
if not matching(s2s(.s1, .i .. .j), .s2): break
if .sublen <= .j - .i {
.l, .r = .i, .j
.sublen = .j - .i
}
}
}
if .r == 0: return ""
s2s .s1, .l .. .r
}
 
writeln .lcs("thisisatest", "testing123testing")
</syntaxhighlight>
 
{{out}}
<pre>test
</pre>
 
=={{header|Lobster}}==
{{trans|Go}}
<langsyntaxhighlight Lobsterlang="lobster">import std
def lcs(a, b) -> string:
var out = ""
Line 1,275 ⟶ 1,660:
greatestLength = lengths[i * b.length + j]
out = a.substring(i - greatestLength + 1, greatestLength)
return out</langsyntaxhighlight>
{{trans|C#}}
<langsyntaxhighlight Lobsterlang="lobster">import std
def lcs2(a, b) -> string:
var out = ""
Line 1,292 ⟶ 1,677:
greatestLength = lengths[j][i]
out = a.substring(i - greatestLength + 1, greatestLength)
return out</langsyntaxhighlight>
 
=={{header|Maple}}==
<code>StringTools:-LongestCommonSubString()</code> returns the longest common substring of two strings.
<code>StringTools:-CommonSubSequence()</code> returns the longest common subsequence() of two strings.
<langsyntaxhighlight Maplelang="maple">StringTools:-LongestCommonSubString("thisisatest","testing123testing");</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The function <code>LongestCommonSubsequence</code> returns the longest common substring, and <code>LongestCommonSequence</code> returns the longest common subsequence.
<langsyntaxhighlight Mathematicalang="mathematica">Print[LongestCommonSubsequence["thisisatest", "testing123testing"]];</langsyntaxhighlight>
{{out}}
<pre>test</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight Modula2lang="modula2">MODULE LCS;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,Write,ReadChar;
Line 1,363 ⟶ 1,748:
 
ReadChar
END LCS.</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Go}}
<langsyntaxhighlight Nimlang="nim"># Longest common substring.
 
import sequtils
Line 1,382 ⟶ 1,767:
result = a[(i - greatestLength + 1)..i]
 
echo lcs("thisisatest", "testing123testing")</langsyntaxhighlight>
 
{{out}}
<pre>test</pre>
 
=={{header|Pascal}}==
=== using FreePascal ===
{{trans|Delphi}}
{{works with|Free Pascal| 3.2.2 }}
<syntaxhighlight lang="pascal">
PROGRAM LongestCommonSubString.pas;
 
 
{$IFDEF FPC}
{$mode objfpc}{$H+}{$J-}{$m+}{$R+}{$T+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
 
(*)
 
Free Pascal Compiler version 3.2.2 [2022/08/01] for x86_64
 
The free and readable alternative at C/C++ speeds
compiles natively to almost any platform, including raspberry PI *
Can run independently from DELPHI / Lazarus
 
https://www.freepascal.org/advantage.var
Version without `USES SysUtils, Variants ;` and without `SubStr`, we do not need it here...
(*)
 
FUNCTION IFF ( Cond: boolean; A, B: string ) : string ;
BEGIN IF ( Cond ) THEN IFF := A ELSE IFF := B ; END ;
 
 
FUNCTION lcss( S1, S2: string ) : string ;
VAR
j : Integer = 0 ;
 
k : Integer = 0 ;
 
S : string = '' ;
BEGIN
 
lcss := '' ;
 
FOR j := 0 TO length ( S1 ) DO BEGIN
FOR k := length ( S1 ) - j DOWNTO 1 DO BEGIN
 
S := Copy(S1, (j + 1), (k + j + 1)) ;
IF ( pos ( S, S2 ) > 0 ) AND
( length ( S ) > length ( lcss ) ) THEN BEGIN
lcss := S ;
BREAK ;
END ;
 
END ;
 
END ;
 
 
END ; (*) FUNCTION lcss (*)
 
 
VAR
 
S1: string = 'thisisatest' ;
 
S2: string = 'testing123testing' ;
 
 
BEGIN
IF ParamCount = 2 THEN BEGIN
 
S1 := IFF( ( ParamStr ( 1 ) > '' ), ParamStr ( 1 ) , S1 );
 
S2 := IFF( ( ParamStr ( 2 ) > '' ), ParamStr ( 2 ) , S1 );
 
END;
Writeln ( 'string A = ', S1 ) ;
Writeln ( 'string B = ', S2 ) ;
WriteLn ( Lcss ( S1, S2 ) ) ;
END. (*) Of PROGRAM LongestCommonSubString.pas (*)
 
(*)
</syntaxhighlight>
<PRE>JPD 2021/06/18
Output:
 
string A = thisisatest
 
string B = testing123testing
 
test
</PRE>(*)
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict ;
use warnings ;
Line 1,421 ⟶ 1,916:
my $longest = longestCommonSubstr( "thisisatest" ,"testing123testing" ) ;
print "The longest common substring of <thisisatest> and <testing123testing> is $longest !\n" ;
</syntaxhighlight>
</lang>
{{out}}
<pre>The longest common substring of <thisisatest> and <testing123testing> is test !</pre>
 
===Alternate letting regex do the work===
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Longest_Common_Substring
Line 1,436 ⟶ 1,931:
my @best;
"$one\n$two" =~ /(.+).*\n.*\1(?{ $best[length $1]{$1}++})(*FAIL)/;
print "$_\n" for sort keys %{ $best[-1] };</langsyntaxhighlight>
{{out}}
test
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function lcs(string a, b)
<span style="color: #008080;">function</span> <span style="color: #000000;">lcs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
integer longest = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
string best = ""
<span style="color: #004080;">string</span> <span style="color: #000000;">best</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
for i=1 to length(a) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer ch = a[i]
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
for j=1 to length(b) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if ch=b[j] then
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
integer n=1
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
while i+n<=length(a)
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
and j+n<=length(b)
<span style="color: #008080;">and</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
and a[i+n]=b[j+n] do
<span style="color: #008080;">and</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">do</span>
n += 1
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if n>longest then
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">longest</span> <span style="color: #008080;">then</span>
longest = n
<span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span>
best = a[i..i+n-1]
<span style="color: #000000;">best</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return best
<span style="color: #008080;">return</span> <span style="color: #000000;">best</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?lcs("thisisatest", "testing123testing")
<span style="color: #0000FF;">?</span><span style="color: #000000;">lcs</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"thisisatest"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"testing123testing"</span><span style="color: #0000FF;">)</span>
?lcs("testing123testing","thisisatest")</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">lcs</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"testing123testing"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"thisisatest"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,472 ⟶ 1,969:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de longestCommonSubstring (Str1 Str2)
(setq Str1 (chop Str1) Str2 (chop Str2))
(let Res NIL
Line 1,488 ⟶ 1,985:
Str2 ) )
Str1 )
(pack Res) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (longestCommonSubstring "thisisatest" "testing123testing")
-> "test"</langsyntaxhighlight>
 
=={{header|PowerShell}}==
 
<langsyntaxhighlight PowerShelllang="powershell">function lcs([String]$isa, [String]$jsb) {
{
if ([String]::IsNullOrEmpty($is) -or [String]::IsNullOrEmpty($js)) {return ""}
if ([String]::IsNullOrEmpty($a) -or [String]::IsNullOrEmpty($b))
$sizeMax, $seen = 0, $false
{
for ($k = -$js.Length; $k -lt $is.Length; ++$k) {
$i,$jreturn = 0,-$k""
}
if (0 -lt $k) {$i,$j = $k,0}
$startIndex, $size = -1, -1
while (($i -lt $is.Length) -and ($j -lt $js.Length)) {
for ($k = 0; while (($ik -lt $isa.Length); -and (++$j -lt $js.Length)k) {
{
if ($is.Chars($i) -eq $js.Chars($j)) {break}
for ($i, $j, $d = $k, 0, 0; ($i -lt $a.Length) -and ($j -lt $b.Length); +=+$i, ++$j) 1
$j += 1{
if ($a.Chars($i) -eq $b.Chars($j))
{
$d += 1
if ($size -lt $d)
{
$startIndex = $i - $d + 1
$size = $d
}
}
else
{
$d = 0
}
$p = $i}
}
while (($i -lt $is.Length) -and ($j -lt $js.Length)) {
for ($k = 1; if ($is.Chars($i)k -nelt $jsb.Chars(Length; ++$j)k) {break}
{
$i += 1
for ($i, $j, $d = 0, $k, 0; ($i -lt $a.Length) -and ($j -lt $b.Length); +=+$i, ++$j) 1
$seen = $true{
}if ($a.Chars($i) -eq $b.Chars($j))
$size = $i - $p{
if ($sizeMax -lt $size)d += {1
$iMax,if ($sizeMaxsize =-lt $p, $sized)
{
$startIndex = $i - $d + 1
$size = $d
}
}
else
{
$d = 0
}
}
}
if ($anssize =-lt ""0)
if ($seen) {
return ""
$ans = $is.Substring($iMax,$sizeMax)
}
return $ansa.Substring($startIndex, $size)
}
 
function Print-Lcs([String]$a, [String]$b)
lcs "thisisatest" "testing123testing"</lang>
{
return "lcs $a $b = $(lcs $a $b)"
}
Print-Lcs 'thisisatest' 'testing123testing'
Print-Lcs 'testing' 'sting'
Print-Lcs 'thisisatest_stinger' 'testing123testingthing'
Print-Lcs 'thisisatest_stinger' 'thisis'
Print-Lcs 'testing123testingthing' 'thisis'
Print-Lcs 'thisisatest' 'thisisatest'</syntaxhighlight>
{{out}}
<pre>
lcs thisisatest testing123testing = test
test
lcs testing sting = sting
lcs thisisatest_stinger testing123testingthing = sting
lcs thisisatest_stinger thisis = thisis
lcs testing123testingthing thisis = thi
lcs thisisatest thisisatest = thisisatest
</pre>
 
=={{header|Prolog}}==
 
<langsyntaxhighlight Prologlang="prolog">common_sublist(A, B, M) :-
append(_, Ma, A),
append(M, _, Ma),
Line 1,554 ⟶ 2,085:
), AllSubstrings),
longest_list(AllSubstrings, [], 0, LongestSubString),
string_chars(Result, LongestSubString).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,562 ⟶ 2,093:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s lcs(a$,b$)
If Len(a$)>Len(b$) : Swap a$,b$ : EndIf
l=Len(a$)
Line 1,577 ⟶ 2,108:
t1$="testing123testing"
t2$="thisisatest"
Debug lcs(t1$,t2$)</langsyntaxhighlight>
{{out}}
<pre>test</pre>
Line 1,585 ⟶ 2,116:
===Python: Idiomatic===
====Python: Using Indexes====
<langsyntaxhighlight lang="python">s1 = "thisisatest"
s2 = "testing123testing"
len1, len2 = len(s1), len(s2)
Line 1,598 ⟶ 2,129:
j1 += 1; j2 += 1
i2 = s2.find(s1[i1], i2+1)
print (s1[ir:jr+1])</langsyntaxhighlight>
{{out}}
<pre>"test"</pre>
Line 1,604 ⟶ 2,135:
====Python: Set of substrings====
From my [https://paddy3118.blogspot.com/2021/02/longest-common-substring-investigation.html explanatory blog post].
<langsyntaxhighlight lang="python">def _set_of_substrings(s:str) -> set:
"_set_of_substrings('ABBA') == {'A', 'AB', 'ABB', 'ABBA', 'B', 'BA', 'BB', 'BBA'}"
len_s = len(s)
Line 1,639 ⟶ 2,170:
ans = lcs_ss(s0, s1, s2)
print(f"\n{repr(s0)}, {repr(s1)}, {repr(s2)} ->> {repr(ans)}")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,657 ⟶ 2,188:
 
Expressed as a composition of pure generic functions:
<langsyntaxhighlight lang="python">'''Longest common substring'''
 
from itertools import accumulate, chain
Line 1,776 ⟶ 2,307:
# MAIN ---
main()
</syntaxhighlight>
</lang>
<pre>test</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ 0 temp put
0 temp put
tuck dup size times
[ 2dup swap
0 temp put
0 swap witheach
[ unrot
over size
over = iff
[ drop
conclude ]
done
rot dip
[ 2dup peek ]
= tuck * +
dup temp take
max temp put ]
2drop
temp take
dup temp share > iff
[ temp release
i^ temp replace
temp put ]
else drop
behead drop ]
2drop
temp take dip
[ temp take split nip ]
split drop ] is lcs ( $ $ --> $ )
 
$ "thisisatest" $ "testing123testing" lcs echo$ cr</syntaxhighlight>
 
{{out}}
 
<pre>test</pre>
 
Line 1,783 ⟶ 2,352:
A chance to show off how to use <code>HashTable</code> types in <i>typed/racket</i>
 
<langsyntaxhighlight lang="racket">#lang typed/racket
(: lcs (String String -> String))
(define (lcs a b)
Line 1,807 ⟶ 2,376:
 
(module+ test
("thisisatest" . lcs . "testing123testing"))</langsyntaxhighlight>
 
{{out}}
Line 1,815 ⟶ 2,384:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub createSubstrings( Str $word --> Array ) {
my $length = $word.chars ;
my @substrings ;
Line 1,838 ⟶ 2,407:
say "The longest common substring of $first and $second is " ~
"{findLongestCommon( $first , $second ) } !" ;
}</langsyntaxhighlight>
{{out}}
<pre>The longest common substring of thisisatest and testing123testing is test !</pre>
 
=== Functional ===
<syntaxhighlight lang="raku" perl6line>sub substrings ($s) { (flat (0..$_ X 1..$_).grep:{$_ ≥ [+] @_}).map: { $s.substr($^a, $^b) } given $s.chars }
sub infix:<LCS>($s1, $s2) { ([∩] ($s1, $s2)».&substrings).keys.sort(*.chars).tail }
 
my $first = 'thisisatest';
my $second = 'testing123testing';
say "The longest common substring between '$first' and '$second' is '{$first LCS $second}'.";</langsyntaxhighlight>
{{out}}
<pre>The longest common substring between 'thisisatest' and 'testing123testing' is 'test'.</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang"refal">$ENTRY Go {
= <Prout <LCS ('thisisatest') 'testing123testing'>>;
};
 
LCS {
(e.X) e.L e.X e.R = e.X;
() e.Y = ;
e.X e.Y, e.X: (s.L e.XL),
e.X: (e.XR s.R)
= <Longest (<LCS (e.XL) e.Y>) <LCS (e.XR) e.Y>>;
};
 
Longest {
(e.X) e.Y, <Lenw e.X>: s.LX e.X2,
<Lenw e.Y>: s.LY e.Y2,
<Compare s.LX s.LY>: '+' = e.X;
(e.X) e.Y = e.Y;
};</syntaxhighlight>
{{out}}
<pre>test</pre>
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program determines the LCSUBSTR (Longest Common Substring) via a function. */
parse arg a b . /*obtain optional arguments from the CL*/
if a=='' then a= "thisisatest" /*Not specified? Then use the default.*/
if b=='' then b= "testing123testing" /* " " " " " " */
say ' string A =' a a /*echo string A to the terminal screen.*/
say ' string B =' b b /* " " B " " " " */
say ' LCsubstr =' LCsubstr(a, b) /*display the Longest Common Substring.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
LCsubstr: procedure; parse arg x,y,,$; #= 0 /*LCsubstr: Longest Common Substring. */
Line 1,872 ⟶ 2,462:
end /*k*/ /* [↑] determine if string _ is longer*/
end /*j*/ /*#: the current length of $ string.*/
return $ /*$: (null if there isn't common str.)*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,881 ⟶ 2,471:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Longest Common Substring
 
Line 1,907 ⟶ 2,497:
next
see subend + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,915 ⟶ 2,505:
=={{header|Ruby}}==
{{trans|C#}}
<langsyntaxhighlight lang="ruby">def longest_common_substring(a,b)
lengths = Array.new(a.length){Array.new(b.length, 0)}
greatestLength = 0
Line 1,932 ⟶ 2,522:
end
 
p longest_common_substring("thisisatest", "testing123testing")</langsyntaxhighlight>
 
{{out}}
Line 1,940 ⟶ 2,530:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn longest_common_substring(s1: &str, s2: &str) -> String {
let s1_chars: Vec<char> = s1.chars().collect();
let s2_chars: Vec<char> = s2.chars().collect();
Line 1,973 ⟶ 2,563:
let lcs = longest_common_substring(s1, s2);
println!("{}", lcs);
}</langsyntaxhighlight>
 
{{out}}
Line 1,991 ⟶ 2,581:
 
Explore and experiment withing the online Scala playgrounds that run in your favorite browser: [https://scalafiddle.io/sf/gWBcnoX/0 ScalaFiddle (ES a.k.a. JavaScript, non JVM)] or [https://scastie.scala-lang.org/IjwsDgJZSrqqp6x42am6Ug Scastie (remote JVM)].
<langsyntaxhighlight lang="scala">def longestCommonSubstringsOptimizedPureFP(left: String, right: String): Option[Set[String]] =
if (left.nonEmpty && right.nonEmpty) {
val (shorter, longer) =
Line 2,055 ⟶ 2,645:
else None
 
println(longestCommonSubstringsOptimizedPureFP("thisisatest", "testing123testing"))</langsyntaxhighlight>
 
{{out}}
Line 2,069 ⟶ 2,659:
 
Explore and experiment withing the online Scala playgrounds that run in your favorite browser: [https://scalafiddle.io/sf/gHtMVf1/0 ScalaFiddle (ES a.k.a. JavaScript, non JVM)] or [https://scastie.scala-lang.org/GbMtJwyEQtW8ioabQU6arw Scastie (remote JVM)].
<langsyntaxhighlight lang="scala">def longestCommonSubstringsOptimizedReferentiallyTransparentFP(left: String, right: String): Option[Set[String]] =
if (left.nonEmpty && right.nonEmpty) {
val (shorter, longer) =
Line 2,135 ⟶ 2,725:
else None
 
println(longestCommonSubstringsOptimizedReferentiallyTransparentFP("thisisatest", "testing123testing"))</langsyntaxhighlight>
 
{{out}}
Line 2,141 ⟶ 2,731:
"Some(Set(test))"
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program longest_common_substring;
print(lcs("thisisatest", "testing123testing"));
 
proc lcs(s1, s2);
if #s1 < #s2 then [s1, s2] := [s2, s1]; end if;
 
loop for l in [#s2, #s2-1..1] do
loop for s in [1..#s2-l+1] do
if (substr := s2(s..s+l)) in s1 then
return substr;
end if;
end loop;
end loop;
 
return "";
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>test</pre>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func createSubstrings(String word) -> Array {
gather {
combinations(word.len+1, 2, {|i,j|
Line 2,156 ⟶ 2,767:
}
 
say findLongestCommon("thisisatest", "testing123testing")</langsyntaxhighlight>
{{out}}
<pre>test</pre>
Line 2,162 ⟶ 2,773:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func lComSubStr<
S0: Sliceable, S1: Sliceable, T: Equatable where
S0.Generator.Element == T, S1.Generator.Element == T,
Line 2,188 ⟶ 2,799:
func lComSubStr(w1: String, _ w2: String) -> String {
return String(lComSubStr(w1.characters, w2.characters))
}</langsyntaxhighlight>
 
Output:
 
<langsyntaxhighlight lang="swift">lComSubStr("thisisatest", "testing123testing") // "test"</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Function Longest_common_substring(string1 As String, string2 As String) As String
Dim i As Integer, j As Integer, temp As String, result As String
Line 2,212 ⟶ 2,823:
Debug.Print Longest_common_substring("thisisatest", "testing123testing")
End Sub
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,221 ⟶ 2,832:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function lcs(string1,string2)
For i = 1 To Len(string1)
Line 2,236 ⟶ 2,847:
 
WScript.Echo lcs(WScript.Arguments(0),WScript.Arguments(1))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,242 ⟶ 2,853:
<pre>
C:\>cscript.exe /nologo lcs.vbs "thisisatest" "testing123testing"
test
</pre>
 
=={{header|V (Vlang)}}==
{{trans|C#}}
<syntaxhighlight lang="v (vlang)">fn main()
{
println(lcs("thisisatest", "testing123testing"))
}
 
fn lcs(a string, b string) string {
mut lengths := map[int]int{}
mut output :=''
mut greatest_length := 0
 
for i, x in a {
for j, y in b {
if x == y {
if i == 0 || j == 0 {lengths[i * b.len + j] = 1} else {lengths[i * b.len + j] = lengths[(i-1) * b.len + j-1] + 1}
if lengths[i * b.len + j] > greatest_length {
greatest_length = lengths[i * b.len + j]
output += x.ascii_str()
}
}
}
}
return output
}</syntaxhighlight>
 
{{out}}
<pre>
test
</pre>
Line 2,247 ⟶ 2,889:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">var lcs = Fn.new { |a, b|
var la = a.count
var lb = b.count
Line 2,271 ⟶ 2,913:
}
 
System.print(lcs.call("thisisatest", "testing123testing"))</langsyntaxhighlight>
 
{{out}}
Line 2,278 ⟶ 2,920:
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
<syntaxhighlight lang "XPL0">string 0;
 
proc LCS(SA, SB, Beg, End);
char SA, SB;
int Beg, End;
int APos, BPos, Len;
[Beg(0):= 0; End(0):= 0; Len:= 0;
APos:= 0;
while SA(APos) # 0 do
[BPos:= 0;
while SB(BPos) # 0 do
[if SA(APos) = SB(BPos) then
[Len:= 1;
while SA(APos+Len) # 0 and SB(BPos+Len) # 0 and
SA(APos+Len) = SB(BPos+Len) do Len:= Len+1;
];
if Len > End(0) - Beg(0) then
[Beg(0):= SA + APos;
End(0):= Beg(0) + Len;
Len:= 0;
];
BPos:= BPos+1;
];
APos:= APos+1;
];
];
 
char S1, S2, It;
int Beg, End;
[S1:= "thisisatest";
S2:= "testing123testing";
LCS(S1, S2, @Beg, @End);
for It:= Beg to End-1 do
ChOut(0, It(0));
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
test
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">sub LCS$(a$, b$)
if len(a$) = 0 or len(b$) = 0 then return "" : endif
while len(b$)
Line 2,292 ⟶ 2,976:
 
print LCS$("thisisatest", "testing123testing")
end</langsyntaxhighlight>
 
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn lcd(a,b){
if(b.len()<a.len()){ t:=a; a=b; b=t; }
foreach n,m in ([a.len()..1,-1],a.len()-n+1){
Line 2,303 ⟶ 2,986:
}
""
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">lcd("testing123testing","thisisatest").println();</langsyntaxhighlight>
{{out}}<pre>test</pre>
885

edits