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.
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.
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.
split() only works with one argument, so I have all words with the punctuation after I split with whitespace.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With