commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Andrew Perepelytsya <apere...@gmail.com>
Subject commons-lang new StringUtils method submission
Date Fri, 10 Sep 2004 07:18:29 GMT
Hello, all.

In our projects I've come across a need to split a string into a
number of fixed-length strings. Sadly, there was no ready-to-use
method in StringUtils, but hopefully, this submission may be valuable.
The method tries to do its best to present a readable result.
Feel free to perform any amendments to conform to commons-lang guidelines.

/**
     * Splits the string into a number of fixed-length
     * strings. Word-wrap is applied to avoid cutting
     * in the middle of the word. In this case the
     * string is shortened.
     *
     * @param s String to split
     * @param maxLineLength maximum length of each line
     *
     * @return an array of lines with <code>length &lt;= maxLineLength</code>
     */
    private String[] splitLinesClean(String s, int maxLineLength) {
        // TODO arg checks with newer commons-lang Validate class

        List lines = new ArrayList();
        int index = 0;
        String[] words = StringUtils.split(s);

        while (index < words.length) {
            StringBuffer sb = new StringBuffer(maxLineLength);

            while (sb.length() < maxLineLength && index < words.length) {
                sb.append(words[index]).append(' ');
                index++;
            }
            if (sb.length() > maxLineLength) {
                // cut last space and word
                sb.deleteCharAt(sb.length() - 1);
                sb.delete(sb.lastIndexOf(" "), sb.length());
                index--;
            }

            lines.add(sb.toString());
        }

        return (String[]) lines.toArray(new String[lines.size()]);
    }


Regards,
Andrew

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message