Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How do I split a string into chunks of a specified length?

807591Apr 4 2008 — edited Apr 6 2008
I'm trying to write a snippet of Java code to perform some string manipulation.

Here are the requirements:

Method signature:
String originalString;

int maxLength;
The method must...

Take originalString and split it an array of smaller chunks.
Each chunk must be precisely equal in length to maxLength, with the possible exception of the last chunk.
The last chunk consists of the remaining characters. Its length is less or equal to maxLength.

Comments

=> The subString() methods of String appear a bit clumsy to implement this logic. I'm inclined to believe there is a shorter way.

=> I came across a snippet of Perl that does it in 1 line, using a Regular Expression:
my @str_parts = $originalString =~ /(.{1,$maxLength})/g;
Using my limited knowledge of Regular Expressions, I attempted to convert this to Java code:
String regExp = "/(.{1," + maxLength + "})/g"; // i.e. /(.{1,maxLength})/g

String[] parts = originalString.split(regExp);
However, it simply dumps the entire string into the first array element. Perhaps because Java uses slightly different rules for RegExp's?

=> I also found a function in PHP that does it: (see http://il.php.net/str_split):

<span class="type">
array str_split ( string $string [, int $split_length ] )
=> Surely Java must have some equivalent? I came accross the Jakarta ORO API, but have not been able to make 'head or tail' of it yet...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 4 2008
Added on Apr 4 2008
42 comments
8,878 views