2

I have a lengthy string and want to break it up into a number of sub-strings so I can display it in a menu as a paragraph rather than a single long line. But I don't want to break it up in the middle of a word (so a break every n characters won't work).

So I want to break the string up by the first occurrence of any of the characters in a String after a certain point (in my case, the characters would be a space and a semi-colon, but they could be anything).

Something like:

String result[] = breakString(baseString, // String
                              lineLength, // int
                              breakChars) // String
Bud
  • 709
  • 2
  • 11
  • 28
  • 2
    Possibly related: [split a string in java into equal length substrings while maintaining word boundaries](http://stackoverflow.com/questions/25853393/split-a-string-in-java-into-equal-length-substrings-while-maintaining-word-bound) – Pshemo Jan 23 '16 at 02:46
  • Do you really want to break the string after a certain point, so every line contains __at least__ `lineLength` characters? Or the paragraph should contain that __at most__, breaking after the last occurence of `breakChars` in `lineLength` characters? – bal Jan 24 '16 at 23:13

2 Answers2

0

Consider splitting by the break chars first and then summing the lengths of the segments that result from that split until you reach your line length.

Hamel Kothari
  • 717
  • 4
  • 11
0

Here is one way. I took "by the first occurrence of any of the characters in a String after a certain point" to mean that the next instance of breakChars after a certain lineLength should be the end of a line. So, breakString("aaabc", 2, "b") would return {"aaab", "c"}.

static String[] breakString(String baseString, int lineLength, String breakChars) {
    // find `lineLength` or more characters of the String, until the `breakChars` string
    Pattern p = Pattern.compile(".{" + lineLength + ",}?" + Pattern.quote(breakChars));

    Matcher m = p.matcher(baseString);
    List<String> list = new LinkedList<>();
    int index = 0;
    while (m.find(index)) {
        String s = m.group();
        list.add(s);

        // find another match starting at the end of the last one
        index = m.end();
    }

    if (index < baseString.length() - 1) {
        list.add(baseString.substring(index));
    }

    return list.toArray(new String[list.size()]);
}
Lucas Ross
  • 1,049
  • 8
  • 17