-3

How to create random strings using Java?

user8618899
  • 13
  • 1
  • 3
  • 4
    With a dictionary containing the "meaningful" words you want, then randomly combine them – nortontgueno Sep 12 '19 at 18:25
  • Random strings or random words? Should the result be meaningful? Should the result split into many tokens(words) or would you like an random string like a hashcode? Is there an requirement about string length - min length, max length? – Huluvu424242 Sep 13 '19 at 17:32
  • Check for duplicate of https://stackoverflow.com/questions/32578239/markov-chains-random-text-based-on-probability-java – Huluvu424242 Sep 13 '19 at 17:39

3 Answers3

2

You need to have some kind of a words stash from which you want to pull random words. Then you just want to join them with random punctuation marks. Check this collection of english words.

Jubick
  • 402
  • 3
  • 15
0

It seems that by meaningful random strings you mean the strings which contain words from dictionary or something. Of course, such strings are not "very random" (and not really good choice for password).

Nevertheless, to implement this rather simple thing, you do following:

Take a csv file containing the words which you think are meaningful. Load the words in a list or something similar.

Randomly pick two or three (or more!) words from the file, and then select some punctuation marks, digits (or nothing), and join the word with them in some random order.

A simple code could be as follows:

import random
def getMeaningfulRandomString(level):
    words = ["doe", "Joe", "lover", "king", "kong", "from", "killer"]
    connectors = ".!#1234567890"
    str = ""
    for i in range(level):
         x = random.randint(0,len(words)-1)
         str += words[x]
         if (random.random() < 0.5):
            str += "".join([connectors[random.randint(0, len(connectors)-1)] for i in range (level)])
    return str

for i in range(10):
    print(getMeaningfulRandomString(3))

This gave me an output like:

from.09from922from.78
Joedoe1#5lover
JoekongJoe
killerJoe005kong
doeJoe676Joe
kongkiller82#Joe#!#
doekingfrom
lover3!6king839from1!5
killerlover095Joe
kong#!0kingdoe022

You can modify it in various ways to get the strings which suits your purpose.

prime_hit
  • 326
  • 1
  • 7
0

You can use RandomStringUtils.Java from Apache Commons:

String randomString = RandomStringUtils.randomAlphanumeric(50)

tostao
  • 2,803
  • 4
  • 38
  • 61