Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
Similar to – Wouter Apr 20 '14 at 11:18
up vote 4 down vote accepted

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}  *)
share|improve this answer

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"} *)
share|improve this answer
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 '14 at 14:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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