Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Partition string into length n chunks

34 views
Skip to first unread message

David G

unread,
May 17, 2012, 4:13:35 AM5/17/12
to
I am sure this is trivially simple, but how do I partition a string into non-overlapping length n chunks? The best I could come up with is chunk[s_, n_] := StringJoin[#] & /@ Partition[Characters[s], n] but this seems overly long-winded.

David Bailey

unread,
May 18, 2012, 5:24:19 AM5/18/12
to
On 17/05/2012 09:13, David G wrote:
> I am sure this is trivially simple, but how do I partition a string into non-overlapping length n chunks? The best I could come up with is chunk[s_, n_] := StringJoin[#]& /@ Partition[Characters[s], n] but this seems overly long-winded.
>

I suspect this is almost as good as you will get, but for speed I would
avoid the pure function:

chunks[s_,n_]:=Map[StringJoin,Partition[Characters[s], n]];

Note that stray characters on the end of the string are just lost.

David Bailey
http://www.dbaileyconsultancy.co.uk

Szabolcs Horvát

unread,
May 18, 2012, 5:27:22 AM5/18/12
to
On 2012.05.17. 10:13, David G wrote:
> I am sure this is trivially simple, but how do I partition a string into non-overlapping length n chunks? The best I could come up with is chunk[s_, n_] := StringJoin[#]& /@ Partition[Characters[s], n] but this seems overly long-winded.
>

This question has been answered here:

http://mathematica.stackexchange.com/questions/5644/partition-string-into-chunks

--
Szabolcs Horvát
Visit Mathematica.SE: http://mathematica.stackexchange.com/

Bob Hanlon

unread,
May 18, 2012, 5:29:55 AM5/18/12
to
A single argument function doesn't need an explicit argument when mapped

chunk[s_String, n_Integer] :=
StringJoin /@ Partition[Characters[s], n]


Bob Hanlon
0 new messages