在空间随机分割一个字符串("")

时间:2016-11-15 23:57:16

标签: java algorithm

我想从给定的字符串创建两个随机子字符串,在加入时会给我以前的字符串。怎么办呢?

实施例: "我的名字是Robert"是完整的字符串,然后子字符串可以像
    sub1:"我的名字"
    sub2:"是Robert"

2 个答案:

答案 0 :(得分:1)

以下将分配一个由字符串长度限定的随机索引,然后生成两个以随机索引分割的子字符串。

Random rand = new Random();  // initialize Random
int index = rand.nextInt(str.length());                // get random integer less than string length
String sub0 = str.substring(0, index);                 // get substring from 0 to the random index value
String sub1 = str.substring(index);                    // get substring from random index value to end

答案 1 :(得分:0)

如果你想在一个随机空间拆分,你可以这样做:

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

输出结果如下:

sentence
with multiple words and spaces

sentence with
multiple words and spaces