Vamsi Rao Vamsi Rao - 24 days ago 7
Java Question

Randomly split a string at space (" ")

I want to create two random substrings from a given string, which on joining will give me my previous string. How can it be done?

Example:
"My name is Robert" is the complete string, then substring can be like

sub1:"My name"

sub2:"is Robert"

Answer

If you want to split at a random space, you can do something like this:

String str = "sentence with multiple words and spaces";

String[] split = str.split(" ");  // split string at every space

Random rand = new Random();
int index = rand.nextInt(split.length); // choose a random space to split at

// Concatenate words before and after the random space
String first = String.join(" ", Arrays.copyOfRange(split, 0, index));                 
String second = String.join(" ", Arrays.copyOfRange(split, index, split.length)); 

System.out.println(first);
System.out.println(second);

Output of this will be something like:

sentence
with multiple words and spaces

or

sentence with
multiple words and spaces