This seems like it should be trivial, but how do I partition a string into length n
substrings? I can of course write something like
chunk[s_, n_] := StringJoin[#] & /@ Partition[Characters[s], n]
so that chunk["ABCDEF",2]
-> {"AB","CD","EF"}
but this appears unnecessarily cumbersome.
Answer
Try this:
StringCases["ABCDEFGHIJK", LetterCharacter ~~ LetterCharacter]
{"AB", "CD", "EF", "GH", "IJ"}
or for more general cases (i.e. not just for letters, but any characters, and for any partition size):
stringPartition1[s_String, n_Integer] := StringCases[s, StringExpression @@ Table[_, {n}]];
It is more elegant though to use Repeated
(thanks rcollyer):
stringPartition2[s_String, n_Integer] := StringCases[s, Repeated[_, {n}]];
stringPartition2["longteststring", 4]
{"long", "test", "stri"}
Comments
Post a Comment