splitting string in java into fixed length chunks

I have seven strings in a program named string1 through string7.

The size of each of the string will be 30 characters.

I will get a input string of unknown length.

I have to split this input string in 30 char strings and then set first substring into string1, 2nd in string2 and so on until possible. If input string is greater then 210 characters then remaining string at the end will be ignored.

How to handle the case when the input string is of size smaller then 210 char.

For e.g. 145 in which case string1 through string4 will be full and string5 will be made of remaining 15 char.

How to handle this nicely ?

I can do it reading char by char and putting first 30 char and string1, next in string2, etc until all char are consumed.

But is there a better way to do this ?

Answer

Since your Strings are not in an array or List you need to assign them explicitely.

    Matcher m = Pattern.compile(".{1,30}").matcher(s);
    String s1 = m.find() ? s.substring(m.start(), m.end()) : "";
    String s2 = m.find() ? s.substring(m.start(), m.end()) : "";
    String s3 = m.find() ? s.substring(m.start(), m.end()) : "";
    String s4 = m.find() ? s.substring(m.start(), m.end()) : "";
    String s5 = m.find() ? s.substring(m.start(), m.end()) : "";
    String s6 = m.find() ? s.substring(m.start(), m.end()) : "";
    String s7 = m.find() ? s.substring(m.start(), m.end()) : "";

Leave a Reply

Your email address will not be published. Required fields are marked *