How to split a string after every 10 words?

Abby44 :

I looking for a way to split my chunk of string every 10 words. I am working with the below code.

My input will be a long string.
Ex: this is an example file that can be used as a reference for this program, i want this line to be split (newline) by every 10 words each.

private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {                                          

    String[] names = jTextArea13.getText().split("\\n");

           var S = names.Split().ToList();
           for (int k = 0; k < S.Count; k++) {
               nam.add(S[k]);
               if ((k%10)==0) { 
                   nam.add("\r\n");       
               }
           }

           jTextArea14.setText(nam);


output:
this is an example file that can be used as
a reference for this program, i want this line to
be split (newline) by every 10 words each.

Any help is appreciated.

Michael Berry :

I am looking for a way to split my chunk of string every 10 words

A regex with a non-capturing group is a more concise way of achieving that:

str = str.replaceAll("((?:[^\\s]*\\s){9}[^\\s]*)\\s", "$1\n");

The 9 in the above example is just words-1, so if you want that to split every 20 words for instance, change it to 19.

That means your code could become:

jTextArea14.setText(jTextArea13.getText().replaceAll("((?:[^\\s]*\\s){9}[^\\s]*)\\s", "$1\n"));

To me, that's much more readable. Whether it's more readable in your case of course depends on whether users of your codebase are reasonably proficient in regex.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=124557&siteId=1