There are three stages to your problem, splitting the String, inserting randomness and using them together...
Splitting a String
Break it into words with String.split(), which creates an array of Strings (in this case words) by spaces.
String[] words = text.split(" "); //Split by spaces
then rebuild your String with newlines added for instance:-
StringBuiler sb = new StringBuilder();
for (String word : words)
{
sb.append(word + "\n");
}
String text2 = sb.toString();
In this case you will insert a newline in between every word and save the result in text2
.
Inserting Randomness
You could just create a Random object...
Random random = new Random();
Then use it in the code that inserts your newline, like so...
//Randomly add or don't add a newline (Compacted with a ternary operator instead of an 'if')
sb.append(word + (random.nextBoolean() ? "\n" : ""));
Bringing it together (TLDR)
Then all you need to do is maintain a count of inserted newlines and limit them to that. So your code becomes:-
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 fits your purpose here it is not the ideal implementation of random (as mentioned in the comments), in that there is more bias towards one appearing nearer the start of the String than the end and that there no chance of it appearing before the first word.
There is also another option of using StringTokenizer instead of String.split() which I much prefer but it doesn't deal with regex and is falling out of use, so I've changed my answer to use String.split()