简体   繁体   English

文本区域文本要按条件分割

[英]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: 我想根据以下条件在我的Java类中分隔行/出现:

When the user does not press the enter key, I want to get substrings (texts) of 10 characters each. 当用户不按Enter键时,我希望获得每个10个字符的子字符串(文本)。 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. 当用户确实按下回车键时,我要将该部分分离出来并再次开始计数直到15以得到一个新的子字符串,直到到达自由流动文本/字符串的末尾为止。

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) 输入密钥为(限制为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. 基本相同,只是没有15个循环或嵌套循环。

I assume when you say "10 characters" you mean 15 characters, right? 我假设您说“ 10个字符”是指15个字符,对不对?

In that case, I use split it first on newlines with a StringTokenizer, and then break each of the results into 15-char chunks. 在这种情况下,我首先使用StringTokenizer在换行符上将其拆分,然后将每个结果分成15个字符的块。 This will give you two loops, an outer one for the StringTokenizer and an inner one for the 15-char chunkifying. 这将给您两个循环,一个用于StringTokenizer的外部循环,一个用于15个字符的块化的内部循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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