Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string after every 10 words?

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.

like image 688
Samantha1154 Avatar asked Jul 31 '19 09:07

Samantha1154


People also ask

How do I split a string after a word?

var theString = "A-quick-brown-fox-jumps-over-the-lazy-dog."; var afterJumps = theString. Split(new[] { "jumps-" }, StringSplitOptions. None)[1]; //Index 0 would be what is before 'jumps-', index 1 is after. Show activity on this post.

How do you split a string into 3 words in Python?

Python 3 - String split() MethodThe split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

Can split () take multiple arguments?

split() only works with one argument, so I have all words with the punctuation after I split with whitespace.


1 Answers

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.

like image 134
Michael Berry Avatar answered Oct 16 '22 06:10

Michael Berry