Introduction
Some time ago, I need to write function which split string in some specific way. At the first look, task looks trivial, but it was not so easy - especially when I want to decrease code size.
Challenge
As example we have following input string (it can be arbitrary)
Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia ...
We need to splitting it into elements ( groups of adjacent words) using following rules (A-E)
"Lorem ipsum dolor", // A: take Three words if each has <6 letters
"sit amet", // B: take Two words if they have <6 letters and third word >=6 letters
"consectetur", // C: take One word >=6 letters if next word >=6 letters
"adipiscing elit", // D: take Two words when first >=6, second <6 letters
"sed doeiusmod", // E: Two words when first<6, second >=6 letters
"tempor" // rule C
"incididunt ut" // rule D
"Duis aute irure" // rule A
"dolor in" // rule B
"reprehenderit in" // rule D
"esse cillum" // rule E
"dolor eu fugia" // rule D
...
So as you can see input string (only alphanumeric characters) is divided to elements (substrings) - each element can have min one and max three words. You have 5 rules (A-E) to divide your string - if you take words one by one from beginning - only one of this rule applied. When you find rule, then you will know how many words move from input to output (1,2 or 3 words) - after that start again: find next rule for the remaining input words.
Boundary conditions: if last words/word not match any rules then just add them as last element (but two long words cannot be newer in one element)
In the output we should get divided string - each element separated by new line or |
(you don't need to use double quotes to wrap each element)
Example Input and Output
Here is example input (only alphanumeric ASCII characters):
Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia
and its output:
Lorem ipsum dolor|sit amet|consectetur|adipiscing elit|sed doeiusmod|tempor|incididunt ut|Duis aute irure|dolor in|reprehenderit in|esse cillum|dolor eu fugia