简体   繁体   中英

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.

Eg, 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
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++ ) {
      current.append(text.charAt(j));
      if( j%15 == 0 ) {
        chunks.add(current.toString());
        current = new StringBuilder(counter);
      }
    }
    chunks.add(current.toString());
    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.

I assume when you say "10 characters" you mean 15 characters, right?

In that case, I use split it first on newlines with a StringTokenizer, and then break each of the results into 15-char chunks. This will give you two loops, an outer one for the StringTokenizer and an inner one for the 15-char chunkifying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM