How to split a string after every 10 words?
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.