5
$\begingroup$

Suppose I have a string myString = "ABC DEF". To split myString into a list of separate strings delimited by " ", I can simply use StringSplit:

myString = "ABC DEF";
StringSplit[myString, " "]
(* {"ABC", "DEF"} *)

Is there an analogous "splitting function" that takes a list as input, rather than a string? For example, suppose I have a list of strings:

myList = {"A", "B", "C", " ", "D", "E", "F"};

I wish to split myList at the " " to obtain two lists. The result I desire is desiredList:

desiredList = {{"A", "B", "C"}, {"D", "E", "F"}}

What function will transform myList into desiredList?

SplitBy comes close, but it retains the delimiter, " ":

SplitBy[myList, # == " " &]
(* {{"A", "B", "C"}, {" "}, {"D", "E", "F"}} *)

I can then use DeleteCases to remove the delimiter, yielding the desired result:

DeleteCases[SplitBy[myList, # == " " &], {" "}]
% == desiredList
(* {{"A", "B", "C"}, {"D", "E", "F"}} *)
(* True *)

Is there a simpler way to accomplish this?

The resource functions "SplitWhen" (ResourceFunction["SplitWhen"]) and "SplitAt" (ResourceFunction["SplitAt"]) come close, but post-processing with DeleteCases is still necessary:

ResourceFunction["SplitWhen"][myList, # == " " &]
Map[DeleteCases[#, " "] &, %]
% == desiredList
ResourceFunction["SplitAt"][myList, # == " " &, After]
Map[DeleteCases[#, " "] &, %]
% == desiredList
ResourceFunction["SplitAt"][myList, # == " " &, Before]
Map[DeleteCases[#, " "] &, %]
% == desiredList
$\endgroup$

2 Answers 2

9
$\begingroup$
SequenceSplit[myList, {" "}]
$\endgroup$
4
$\begingroup$

Here are older alternatives:

SplitBy[myList, # === " " &][[;; ;; 2]]

SequenceCases[myList, {Except[" "] ..}]
$\endgroup$
1
  • 2
    $\begingroup$ Since OP wanted an equivalent of StringSplit for lists it should be noted that your code (same as @lericr) behaves differently from StringSplit when there are consecutive delimiters. For example in output of StringSplit["abc de fgh i", " "] there is one empty string "" but if you apply your code to Characters@"abc de fgh i" there will be missing empty list {}. Version with SequenceCases can be modified with ... instead of .. to achieve an analogue result. $\endgroup$ Commented Oct 17 at 23:23

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.