Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create New String with Several Random New Line

I have a string:

String text = "Nothing right in my brain. Nothing left in my brain"

I want to create a new string text2 that has 2-4 random new line from previous, such as:

"Nothing \n right \n in my brain.  \n Nothing left in my brain"

or

"Nothing right in \n my brain. Nothing left in \n my brain"

How to create a new string with random new line between the words? I am thinking to get the index of whitespace, in order to insert new line after random whitespace. But I only keep getting the first whitespace index. Anyone know better approach to solve this? Thank you.

like image 847
Lynx Avatar asked Jun 26 '15 11:06

Lynx


People also ask

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

Can we generate random string?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer. The ints() method from java. util.

How do you generate a random text string in Java?

Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string.

How do you write a new line in RandomAccessFile?

String data = "New Line"; RandomAccessFile raf = new RandomAccessFile(myFile); raf. writeBytes("\r\n" + data); This will add a new line (windows style / CRLF) before the "text".


2 Answers

There are three stages to your problem, splitting the String, inserting randomness and using them together...

Splitting a String

Break it into words with String.split(), which creates an array of Strings (in this case words) by spaces.

  String[] words = text.split(" "); //Split by spaces

then rebuild your String with newlines added for instance:-

 StringBuiler sb = new StringBuilder();
 for (String word : words)
 {
   sb.append(word + "\n");
 }
 String text2 = sb.toString();

In this case you will insert a newline in between every word and save the result in text2.

Inserting Randomness

You could just create a Random object...

    Random random = new Random(); 

Then use it in the code that inserts your newline, like so...

//Randomly add or don't add a newline (Compacted with a ternary operator instead of an 'if')
sb.append(word + (random.nextBoolean() ? "\n" : ""));

Bringing it together (TLDR)

Then all you need to do is maintain a count of inserted newlines and limit them to that. So your code becomes:-

 int requiredNewlines = random.nextInt(2 - 5) + 2; //Number between 2-4
 for (String word : words) //For each word
 {
   sb.append(word); //Add it
   if (requiredNewlines >= 0 && random.nextBoolean()) 
   {
   //Randomly add newline if we haven't used too many
      sb.append("\n"); 
      requiredNewlines--;
   }
 }
 String text2 = sbAppen.toString();

Additionally

Although the randomness in this example fits your purpose here it is not the ideal implementation of random (as mentioned in the comments), in that there is more bias towards one appearing nearer the start of the String than the end and that there no chance of it appearing before the first word.

There is also another option of using StringTokenizer instead of String.split() which I much prefer but it doesn't deal with regex and is falling out of use, so I've changed my answer to use String.split()

like image 111
Ross Drew Avatar answered Sep 30 '22 13:09

Ross Drew


First you need a new random from 2-4:

int max = 4;
int min = 2;

Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;

After split string into words:

String[] words = text.split(" ");

Then, get 4 different numbers from 1 to words.length

ArrayList<Integer> randomPositions = new ArrayList<Integer>(randomNum);
max = words.length;
min = 1;
for (int count = 0; count < randomNum; count ++) {
   int random = rand.nextInt((max - min) + 1) + min;
   if (randomPositions.contains(random)) count --;
   else randomPositions.add(random);
}

Finally put \n in positions when rebuilding the array:

StringBuilder result = new StringBuilder();
for (int count = 0; count < max; count ++) {
    result.append(words[count]);
    if (randomPositions.contains(count))
        result.append("\n");
    else
        result.append(" ");
}

Check this working demo

Output1:

Nothing right in my
brain. Nothing
left in my brain 

Output2:

Nothing right
in my brain. Nothing left
in my
brain 

Output3:

Nothing right in my brain. Nothing left
in my brain 
like image 36
Jordi Castilla Avatar answered Sep 30 '22 12:09

Jordi Castilla