2
$\begingroup$

I have this list of strings; first string overlaps with the second string, and second string overlaps with the third string. I want to combine those into a single paragraph.

str = {"Raymond went for a walk in downtown and had so much fun being \
there. After 6 o'clock he had to return for supper.", 
   "After 6 o'clock he had to return for supper. Yet, despite all his \
willpower and best efforts, he could not get going back.", 
   "Yet, despite all his willpower and best efforts, he could not get \
going back. So he decided to stay."};

Expected output: "Raymond went for a walk in downtown and had so much fun being there.
After 6 o'clock he had to return for supper. Yet, despite all his
willpower and best efforts, he could not get going back. So he
decided to stay."

$\endgroup$

1 Answer 1

4
$\begingroup$

Apply Fold[] and SequenceAlignment[...,Method->"Local"]

Fold[StringJoin[SequenceAlignment[#1, #2, Method -> "Local"]] &, str]

Output:

"Raymond went for a walk in downtown and had so much fun being there.
After 6 o'clock he had to return for supper. Yet, despite all his
willpower and best efforts, he could not get going back. So he
decided to stay."

Should you encounter a situation where the above does not work with your text...

...Here is a custom solution:

MWhatToJoin[s1_, s2_] := Module[{posoverlap, pos1, pos2},
  posoverlap = LongestCommonSubsequencePositions[s1, s2];
  If[SameQ[posoverlap, {}], Return[{s1, s2}]];
  If[And[posoverlap[[1, 2]] == StringLength[s1], 
   posoverlap[[2, 1]] == 1], 
   Return[{s1, StringTake[s2, {posoverlap[[2, 2]] + 1, -1}]}]];
  If[And[posoverlap[[2, 2]] == StringLength[s2], 
   posoverlap[[1, 1]] == 1], 
   Return[{s2, StringTake[s1, {posoverlap[[1, 2]] + 1, -1}]}]];
  Return[{s1, s2}]
  ]
MJoinTextWithoutOverlap[s1_, s2_, separator_ : ""] := 
 Module[{ls1, ls2},
  {ls1, ls2} = MWhatToJoin[s1, s2];
  Return[StringJoin[ls1, separator, ls2]]
  ]

For overlap instances in MWhatToJoin[], consider replacing the functions in Return[...] with SequenceAlignment[...,Method->"Local"].

$\endgroup$

Your Answer

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

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