5
$\begingroup$

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?

$\endgroup$
4
$\begingroup$

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}  *)
$\endgroup$
3
$\begingroup$

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"} *)

Original answer:

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"} *)
$\endgroup$
  • $\begingroup$ 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). $\endgroup$ – Cray Apr 19 '14 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.