java - Create New String with Several Random New Line -
i have string:
string text = "nothing right in brain. nothing left in brain"
i want create new string text2
has 2-4 random new line previous, such as:
"nothing \n right \n in brain. \n nothing left in brain"
or
"nothing right in \n brain. nothing left in \n brain"
how create new string random new line between words? thinking index of whitespace, in order insert new line after random whitespace. keep getting first whitespace index. know better approach solve this? thank you.
there 3 stages problem, splitting string, inserting randomness , using them together...
splitting string
break words string.split(), creates array of strings (in case words) spaces.
string[] words = text.split(" "); //split spaces
then rebuild string newlines added instance:-
stringbuiler sb = new stringbuilder(); (string word : words) { sb.append(word + "\n"); } string text2 = sb.tostring();
in case insert newline in between every word , save result in text2
.
inserting randomness
you create random object...
random random = new random();
then use in code inserts newline, so...
//randomly add or don't add newline (compacted ternary operator instead of 'if') sb.append(word + (random.nextboolean() ? "\n" : ""));
bringing (tldr)
then need maintain count of inserted newlines , limit them that. code becomes:-
int requirednewlines = random.nextint(2 - 5) + 2; //number between 2-4 (string word : words) //for each word { sb.append(word); //add if (requirednewlines >= 0 && random.nextboolean()) { //randomly add newline if haven't used many sb.append("\n"); requirednewlines--; } } string text2 = sbappen.tostring();
additionally
although randomness in example fits purpose here not ideal implementation of random (as mentioned in comments), in there more bias towards 1 appearing nearer start of string end , there no chance of appearing before first word.
there option of using stringtokenizer instead of string.split() prefer doesn't deal regex , falling out of use, i've changed answer use string.split()
Comments
Post a Comment