6

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.

Sponge Bob
  • 765
  • 1
  • 8
  • 17

2 Answers2

8

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.

Rojo
  • 42,601
  • 7
  • 96
  • 188
4

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.

kale
  • 10,922
  • 1
  • 32
  • 69