views:

285

answers:

2

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
A: 

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.

Paul A Jungwirth
tequila makes me chunkify
Jason
docs say stop using StringTokenizer. it's only kept around for backwards compatibility.
geowa4
Thanks Paul,yes 10 or 15 ... the problem here lies in getting the count of lines/rows...after i get a row i need to do some operation and also have a counter of the rows
+1  A: 
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.

geowa4
Thanks George.Just that i am not sure whether this will give the chunks in sequence:For my eg i will get three chunks:1.Hello I want (assuming the user pressed enter key at this point)==>after getting this i number this as sequence#12.enter key to be==>after getting this chunk i need to number this as #23.caught ==>this has to be my third chunk with sequence#3
edited: i forgot about new lines.
geowa4
Hi George... just that if i split then i am losing out the '/n'.But in case there are any text entered before the user presses enter key,i need to keep those lines also in my item with proper sequence number.Only if the user presses enter key without adding any text i need to remove such items....any help?
'/n' to be removed'/n' to be removedtext entered and then key '/n' ==> to be retaines'/n' to be retained'n' to be retainedbetween text entered lines...