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...