Vamsi Rao Vamsi Rao - 1 year ago 174
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?

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

sub1:"My name"

sub2:"is Robert"

Answer Source

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)); 


Output of this will be something like:

with multiple words and spaces


sentence with
multiple words and spaces