# Finding all instances of length $N$ common subwords in two strings

Given a pair of strings, I'd like to return a list of all common subwords of a fixed length of "n" characters (i.e. contiguous subwords of length "n" that occur in both strings), allowing for overlaps. Is there a built-in or close-to-built-in way to do this in Mathematica?

• Apr 20, 2014 at 11:18

No intrinsic function to do that, but easy enough:

commonWords[string1_, string2_, length_] :=
StringJoin /@ Intersection[Partition[Characters[string1], length, 1],
Partition[Characters[string2], length, 1]]

stringA = "Thisisatest"
stringB = "Thisisanothertest"

commonWords[stringA, stringB, 3]

(*  {est,his,isa,isi,sis,tes,Thi}  *)


Update: a simpler/faster alternative:

cmmnwrdsF2 = Intersection @@
StringCases[{#1, #2}, Repeated[_, {#3}], Overlaps -> True] &
cmmnwrdsF2[stringA, stringB, 3]
(* {"est", "his", "isa", "isi", "sis", "tes", "Thi"} *)


cmmnwrdsF = DeleteDuplicates[
Join @@ StringCases[(SequenceAlignment[#1, #2] /. {_, _} :> Sequence[]),
Repeated[_, {#3}], Overlaps -> True]] &
stringA = "Thisisatest";
stringB = "Thisisanothertest";
cmmnwrdsF[stringA, stringB, 3]
(* {"Thi", "his", "isi", "sis", "isa", "tes", "est"}  *)
cmmnwrdsF[stringA, stringB, 4]
(* {"This", "hisi", "isis", "sisa", "test"} *)

• Great, another method! FYI for readers, $n = 3$ examples in this method and rasher's method match up (but are just out of order with respect to one-another).
– Cray
Apr 19, 2014 at 14:25