# Split string into sub-strings of length n [duplicate]

Possible Duplicate:
Partition string into chunks

How can I split a string into sub strings of length n? For example I have a string

"ABCDEabcde1234"


I would like to split it into

{"AB", "CD", "Ea", "bc", "de", "12", "34"}


How can I achieve this? I have looked at the StringSplit[] documentation but that seems like it only works for splitting a string by character, not length.

-

## marked as duplicate by Ｊ. Ｍ.Oct 3 '12 at 18:59

I see a multitude of answers coming! Perfect for non-experts. –  István Zachar Oct 3 '12 at 18:04
@IstvánZachar it may very well give experts a run for their money, too. As there are a lot of choices. –  rcollyer Oct 3 '12 at 18:10
As a first hint: look up Partition[] and Characters[]. –  Ｊ. Ｍ. Oct 3 '12 at 18:11
I will restrain myself for an hour... –  Sjoerd C. de Vries Oct 3 '12 at 18:12
Related question (Partition string into chunks) –  TomD Oct 3 '12 at 18:56

I think @OleksandrR once suggested to me in chat this solution

stringPartition[s_, n_]:=StringCases[s, Repeated[_, n]]


The key is that the option Overlaps defaults to False. If you want to be on the safe side you can add it explicitly

If you want the last part to be removed if it doesn't have n elements, you could use Repeated[_, {n}] instead.

-
The regex equivalent: StringCases[str, RegularExpression[".{1," <> ToString[k] <> "}"]] –  Ｊ. Ｍ. Oct 3 '12 at 18:42

Try this:

splitstring[String : str_, n_] := StringJoin @@@ Partition[Characters[str], n, n, 1, {}]

In[116]:= splitstring["ABCDEabcde1234", 2]

Out[116]= {"AB", "CD", "Ea", "bc", "de", "12", "34"}


As J.M. notes below:

splitstring[String : str_, n_] := StringJoin @@@ Partition[Characters[str], n]


works just as well, but will drop characters at the end if your string length isn't a multiple of n.

So choose based on your need.

-
...the non-expert answer. –  kale Oct 3 '12 at 18:20
StringJoin @@@ Partition[Characters[str], n] works just as well. –  Ｊ. Ｍ. Oct 3 '12 at 18:21
@J.M., only if you have a multiple of the partition size. Right? Your way drops characters at the end in some instances. –  kale Oct 3 '12 at 18:22
@J.M. If the string was a character longer, it would be lost with a partition size of two. splitstring["ABCDEabcde12345", 2] outputs {"AB", "CD", "Ea", "bc", "de", "12", "34"}. –  kale Oct 3 '12 at 18:25
True. I suppose that depends on whether the length of OP's strings would always be commensurate with the partition length... –  Ｊ. Ｍ. Oct 3 '12 at 18:28