2016-11-15 6 views
0

与えられた文字列から2つのランダムな部分文字列を作成します。結合すると以前の文字列が返されます。どのようにそれを行うことができますか?スペースで文字列を無作為に分割する( "")

例:「私の名前」
SUB2:「であるロバート」

+0

入力と出力の例を示して、意味を正確に示します。あなたがこれまでに試したことを示してください。それらがなければ、私たちは手助けできません。 – nhouser9

+0

あなたの質問のタイトルは身体と何が関係していますか? – shmosel

答えて

0

あなたはランダムな間隔で分割したい場合、あなたはこのような何かを行うことができます。

sentence 
with multiple words and spaces 

または

:この

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 
1

以下はランダムなインデックスを割り当てます は「私の名前はロバートある」は、完全な文字列で、その後、サブストリングは
SUB1のようにすることができます文字列の長さによって制限され、次にランダムインデックスで分割された2つの部分文字列を生成します。

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 
+0

なぜ明示的なシードを使用していますか? – shmosel

+0

@shmosel習慣私は – Dando18

+0

@shmoselと思っています。簡略化のために削除しました – Dando18

関連する問題