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$
1

2 Answers 2

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$
0
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$
1
  • $\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, 2014 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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