Find the longest common substring in the given two strings.
Let us limit ourselves with finding only the first longest substring. If there are more common substrings of the same length, then the rest are ignored. There are two loops (see also Task 17, The longest palindrome) over the first string ($a
), and they use the indexmethod to search for the substring in the second string ($b
).
my $a = 'the quick brown fox jumps over the lazy dog';
my $b = 'what does the fox say?';
my $common =Â '';
for 0 .. $a.chars -> $start {
    for $start .. $a.chars - 1 -> $end {
        my $s = $a.substr($start, $a.chars - $end);
        if $s.chars > $common.chars && $b.index($s).defined {
           $common = $s;
        }
    }
}
say $commonÂ
    ?? "The longest common substring is '$common'."Â
    !! 'There are no common substrings.';
The index
method returns the position of the substring $s
if it is found in the string $b
. It is a little bit tricky to check if the substring is found because when it is found at the beginning of the string, then the returned value is 0 (as 0 is the position of the substring). If the substring is not found, then Nil
is returned. Nil
is not a numeric value; thus, it cannot be compared using the ==
or !=
operators. Use the defined
method to check if index
returns a value, not Nil
:Â $b.index($s).defined
.
Can’t decide if I like this version better or worse than yours:
argh, formatting fail!
Fixed 🙂