Java – Text area text to be split with conditions


I have a text area where a user can enter free flow text. I want to separate out lines/occurrences in my Java class based on the below conditions:

When the user does not press the enter key, I want to get substrings (texts) of 10 characters each. When the user does press enter, I want to separate that part out and start again counting till 15 to get a new substring till I reach the end of the free flow text/string.

If user enters:

Hello I want
enter key to be caught.

I want this text to be separated into the below substrings:

  1. Hello I want (assuming the user pressed enter key at this point)
  2. enter key to be (as the limit is 15)
  3. caught

Best Solution

if( text.contains("\n") ) {

  counter = 15;
  String[] splitText = text.split("\n");
  ArrayList<String> chunks - new ArrayList<String>(text.length%counter+1);
  StringBuilder current = new StringBuilder(counter);

  for( int i = 0; i < splitText.length; i++ ) {
    for( int j = 0; j < splitText[i].length; j++ ) {
      if( j%15 == 0 ) {
        current = new StringBuilder(counter);
    current = new StringBuilder(counter);


With that you can figure out the other requirement you had. It's basically the same just not with 15 or nested loops.