There are three steps to your problem: splitting String , inserting randomness and using them together ...
String separation
Divide it into words using String.split () , which creates an array of strings (in this case words) with spaces.
String[] words = text.split(" ");
then rebuild String with new lines added: -
StringBuiler sb = new StringBuilder(); for (String word : words) { sb.append(word + "\n"); } String text2 = sb.toString();
In this case, you insert a new line between each word and save the result in text2 .
Randomness insert
You can just create a Random object ...
Random random = new Random();
Then use it in code that inserts your new line, for example ...
//Randomly add or don't add a newline (Compacted with a ternary operator instead of an 'if') sb.append(word + (random.nextBoolean() ? "\n" : ""));
Association (TL; DR)
Then you only need to save the number of inserted rows and limit them. So your code will be: -
int requiredNewlines = random.nextInt(2 - 5) + 2; //Number between 2-4 for (String word : words) //For each word { sb.append(word); //Add it if (requiredNewlines >= 0 && random.nextBoolean()) { //Randomly add newline if we haven't used too many sb.append("\n"); requiredNewlines--; } } String text2 = sbAppen.toString();
Additionally
Although the randomness in this example matches your purpose here, it is not an ideal implementation of random ones (as mentioned in the comments), as there is a more biased attitude towards what is approaching the beginning of the String and that there is no chance that it will appear before the first word.
There is another option for using StringTokenizer instead of String.split () , which I prefer but does not deal with regex and does not work, so I changed my answer to using String.split ()