Есть ли возможность генерировать случайный символ в Java?
Есть ли у Java какие-либо функции для генерации случайных символов или строк? Или нужно просто выбрать случайное целое число и преобразовать этот целочисленный код ascii в символ?
ОТВЕТЫ
Ответ 1
Существует много способов сделать это, но да, это включает в себя создание случайного int (используя, например, java.util.Random.nextInt ), а затем используя это для сопоставления с char . Если у вас есть определенный алфавит, то что-то вроде этого отличное:
import java.util.Random; //. Random r = new Random(); String alphabet = "123xyz"; for (int i = 0; i < 50; i++) < System.out.println(alphabet.charAt(r.nextInt(alphabet.length()))); >// prints 50 random characters from alphabet
Отметим, что java.util.Random на самом деле является генератором псевдослучайных чисел на основе довольно слабой линейная конгруэнтная формула. Вы упомянули о необходимости криптографии; вы можете изучить использование более сильного криптографически защищенного генератора псевдослучайных чисел в этом случае (например, java.security.SecureRandom ).
Ответ 2
Чтобы создать случайный char в a-z:
Random r = new Random(); char c = (char)(r.nextInt(26) + 'a');
Ответ 3
Вы также можете использовать RandomStringUtils из проекта Apache Commons:
RandomStringUtils.randomAlphabetic(stringLength);
Ответ 4
private static char rndChar () < int rnd = (int) (Math.random() * 52); // or use Random or whatever char base = (rnd
Генерирует значения в диапазонах a-z, A-Z.
Ответ 5
В соответствии с 97 значением ascii малого "a".
public static char randomSeriesForThreeCharacter()
в выше 3 числа для a, b, c или d, и если u хочет, чтобы все символы, такие как a-z, вы заменяли 3 числа на 25.
Ответ 6
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char letter = abc.charAt(rd.nextInt(abc.length()));
Ответ 7
Чтобы создать случайную строку, используйте метод anyString.
Вы можете создавать строки из более ограниченного набора символов или с ограничениями минимального/максимального размера.
Обычно вы запускаете тесты с несколькими значениями:
@Test public void myTest() < for (Listany : someLists(integers())) < //A test executed with integer lists >>
Ответ 8
Iterable chars = $('a', 'z'); // 'a', 'b', c, d .. z
данный chars вы можете создать "перетасованный" диапазон символов:
Iterable shuffledChars = $('a', 'z').shuffle();
затем беря первые символы n , вы получите случайную строку длины n . Окончательный код просто:
public String randomString(int n)
NB: условие n > 0 перечеркнуто slice
как правильно указал Стив, randomString использует не более одного раза каждую букву. Как обходной путь вы можете повторить алфавит m раз перед вызовом shuffle :
public String randomStringWithRepetitions(int n)
или просто укажите свой алфавит как String :
public String randomStringFromAlphabet(String alphabet, int n) < return $(alphabet).shuffle().slice(n).toString(); >String s = randomStringFromAlphabet("00001111", 4);
Ответ 9
public static String generateCode()
Ответ 10
У тебя это есть. Просто создайте случайные коды ASCII самостоятельно. Для чего вам это нужно?
Ответ 11
Взгляните на класс Java Randomizer. Я думаю, вы можете рандомизировать символ, используя метод randomize (char []).
Ответ 12
Ответ Polygenelubricants также является хорошим решением, если вы хотите генерировать только шестнадцатеричные значения:
/** A list of all valid hexadecimal characters. */ private static char[] HEX_VALUES = < '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F' >; /** Random number generator to be used to create random chars. */ private static Random RANDOM = new SecureRandom(); /** * Creates a number of random hexadecimal characters. * * @param nValues the amount of characters to generate * * @return an array containing nValues
hex chars */ public static char[] createRandomHexValues(int nValues) < char[] ret = new char[nValues]; for (int i = 0; i < nValues; i++) < ret[i] = HEX_VALUES[RANDOM.nextInt(HEX_VALUES.length)]; >return ret; >
Ответ 13
Мое предложение для генерации случайной строки со смешанным случаем типа: "DthJwMvsTyu".
Этот алгоритм основан на кодах ASCII букв, когда его коды az (от 97 до 122) и AZ (от 65 до 90) отличаются в 5-м бите (2 ^ 5 или 1
random.nextInt(2) : результат равен 0 или 1.
Верхний A равен 65, а нижний a равен 97. Разница только на 5-м бите (32), поэтому для генерации случайного символа мы делаем двоичный код OR '|' случайный charCaseBit (0 или 32) и случайный код от A до Z (от 65 до 90).
public String fastestRandomStringWithMixedCase(int length) < Random random = new Random(); final int alphabetLength = 'Z' - 'A' + 1; StringBuilder result = new StringBuilder(length); while (result.length() < length) < final char charCaseBit = (char) (random.nextInt(2) return result.toString(); >
Ответ 14
Вот код для генерации случайного буквенно-цифрового кода. Сначала вы должны объявить строку разрешенных символов, которую вы хотите включить в случайное число, а также определить максимальную длину строки.
SecureRandom secureRandom = new SecureRandom(); String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; StringBuilder generatedString= new StringBuilder(); for (int i = 0; i
Используйте метод toString(), чтобы получить String из StringBuilder
Ответ 15
Это простое, но полезное открытие. Он определяет класс с именем RandomCharacter с 5 перегруженными методами для случайного получения определенного типа символов. Вы можете использовать эти методы в ваших будущих проектах.
public class RandomCharacter < /** Generate a random character between ch1 and ch2 */ public static char getRandomCharacter(char ch1, char ch2) < return (char) (ch1 + Math.random() * (ch2 - ch1 + 1)); >/** Generate a random lowercase letter */ public static char getRandomLowerCaseLetter() < return getRandomCharacter('a', 'z'); >/** Generate a random uppercase letter */ public static char getRandomUpperCaseLetter() < return getRandomCharacter('A', 'Z'); >/** Generate a random digit character */ public static char getRandomDigitCharacter() < return getRandomCharacter('0', '9'); >/** Generate a random character */ public static char getRandomCharacter() < return getRandomCharacter('\u0000', '\uFFFF'); >>
Чтобы продемонстрировать, как это работает, давайте взглянем на следующую тестовую программу, отображающую 175 случайных строчных букв.
public class TestRandomCharacter < /** Main method */ public static void main(String[] args) < final int NUMBER_OF_CHARS = 175; final int CHARS_PER_LINE = 25; // Print random characters between 'a' and 'z', 25 chars per line for (int i = 0; i < NUMBER_OF_CHARS; i++) < char ch = RandomCharacter.getRandomLowerCaseLetter(); if ((i + 1) % CHARS_PER_LINE == 0) System.out.println(ch); else System.out.print(ch); >> >
если вы запустите еще раз:
Я отдаю должное Ю.Даниэлю Лянгу за его книгу " Введение в программирование на Java, полная версия", 10-е издание, где я привел эти знания.
Ответ 16
Если вы не возражаете добавить новую библиотеку в свой код, вы можете генерировать символы с помощью MockNeat (отказ от ответственности: я один авторов).
MockNeat mock = MockNeat.threadLocal(); Character chr = mock.chars().val(); Character lowerLetter = mock.chars().lowerLetters().val(); Character upperLetter = mock.chars().upperLetters().val(); Character digit = mock.chars().digits().val(); Character hex = mock.chars().hex().val();
Ответ 17
Random randomGenerator = new Random(); int i = randomGenerator.nextInt(256); System.out.println((char)i);
Позаботьтесь о том, что вы хотите, считая, что вы считаете "0", "1", "2".. как символы.
Java generate random string
Java provides many different ways to generate a random string and this post will explain most of those.
Generation of random sequence of characters is often required
- to create a unique identifier such as transaction ids in banking applications.
- as a random password generator which provides a temporary password for user registering for the first time on a website.
- Random string for creating captcha to prevent automated input etc.
Method 1 : Using UUID
java.util.UUID class can be used to get a random string. Its static randomUUID method acts as a random alphanumeric generator and returns a String of 32 characters.
If you want a string of a fixed length or shorter than 32 characters, you can use substring method of java.lang.String .
Example,
import java.util.UUID; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingUUID(); System.out.println("Random string is: " + randomString); System.out.println("Random string of 8 characters is: " + randomString.substring(0, 8)); >static String usingUUID() < UUID randomUUID = UUID.randomUUID(); return randomUUID.toString().replaceAll("-", ""); >>
Note that the string generated by randomUUID method contains “–“. Above example removes those by replacing them with empty string.
Output of above program will be
Random string is: 923ed6ec4d04452eaf258ec8a4391a0f
Random string of 8 characters is: 923ed6ec
Method 2 : Using Math class
Following algorithm can be used to generate a random alphanumeric string of fixed length using this method.
- Initialize an empty string to hold the result.
- Create a combination of upper and lower case alphabets and numerals to create a super set of characters.
- Initiate a loop for with count equal to the length of random string required.
- In every iteration, generate a random number between 0 and the length of super set.
- Extract the character from the string in Step 2 at the index of number generated in Step 4 and add it to the string in Step 1.
After the loop completes, string in Step 1 will be a random string.
import java.util.Math; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingMath(); System.out.println("Random string is: " + randomString); >static String usingMath() < String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // create a super set of all characters String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers; // initialize a string to hold result StringBuffer randomString = new StringBuffer(); // loop for 10 times for (int i = 0; i < 10; i++) < // generate a random number between 0 and length of all characters int randomIndex = (int)(Math.random() * allCharacters.length()); // retrieve character at index and add it to result randomString.append(allCharacters.charAt(randomIndex)); >return randomString.toString(); > >
Output of above program executed thrice is
Random string is: kqNG2SYHeF
Random string is: lCppqqUg8P
Random string is: GGiFiEP5Dz
This approach gives you more control over the characters that need to be included in the random string.
For example, if you do not want numbers, then remove them from the super set. If you want special characters, then add a set of special characters in the super set.
Method 3 : Using Random class
This method follows a similar approach as the above method in that a super set of all the characters is created, a random index is generated and character at that index is used to create the final string.
But this approach uses java.util.Random class to generate a random index. Example,
import java.util.Random; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingRandom(); System.out.println("Random string is: " + randomString); >static String usingRandom() < String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // create a super set of all characters String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers; // initialize a string to hold result StringBuffer randomString = new StringBuffer(); // loop for 10 times for (int i = 0; i < 10; i++) < // generate a random number between 0 and length of all characters int randomIndex = random.nextInt(allCharacters.length()); // retrieve character at index and add it to result randomString.append(allCharacters.charAt(randomIndex)); >return randomString.toString(); > >
You can also use java.util.SecureRandom class to generate a random integer. It is a subclass of java.util.Random .
Output of three executions of above program is
Random string is: TycOBOxITs
Random string is: 7LLWVbg0ps
Random string is: p6VyqdO6bT
Method 4 : Using RandomStringUtils
Apache Commons Lang library has an org.apache.commons.lang.RandomStringUtils class with methods to generate random string of a fixed length.
It has methods that can generate a random string of only alphabets( randomAlphabetic ), numbers( randomNumeric ) or both( randomAlphanumeric ).
All these methods accept an integer argument which represents the length of the string that they will generate.
Below is an example.
import org.apache.commons.lang.RandomStringUtils; public class RandomStringGenerator < public static void main(String[] args) < // generate a random string of 10 alphabets String randomString = RandomStringUtils.randomAlphabetic(10); System.out.println("Random string of 10 alphabets: " + randomString); randomString = RandomStringUtils.randomNumeric(10); System.out.println("Random string of 10 numbers: " + randomString); randomString = RandomStringUtils.randomAlphanumeric(10); System.out.println("Random string of 10 alphanumeric characters: " + randomString); >>
Output of above program is
Random string of 10 alphabets: OEfadIYfFm
Random string of 10 numbers: 1639479195
Random string of 10 alphanumeric characters: wTQRMXrNY9
This class also has a method random() that takes an integer which is the length of the string to be generated and a char array. Random string generated consists of only characters from this array.
Apache Commons Lang can be included into your project by adding the below dependency as per the build tool.
org.apache.commons commons-lang3 3.9
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
Method 5 : Using java 8 Stream
With Java 8 streams , we can generate a random alphanumeric string of fixed length.
The idea is to generate a stream of random numbers between ASCII values of 0-9, a-z and A-Z, convert each integer generated into corresponding character and append this character to a StringBuffer.
Example code is given below
import java.util.Random; public class RandomStringGenerator < public static void main(String[] args) throws IOException < Random r = new Random(); String s = r.ints(48, 123) .filter(num ->(num < 58 || num >64) && (num < 91 || num >96)) .limit(10) .mapToObj(c -> (char) c).collect(StringBuffer::new, StringBuffer::append, StringBuffer::append) .toString(); System.out.println('Random alphanumeric string is: " + s); > >
java.util.Random class has a new method ints() added in java 8.
ints() takes two integer arguments and generates a stream of integers between those two integers with start inclusive and end exclusive.
This stream is filtered with filter() method to include ASCII values of only 0-9, a-z and A-Z.
If you want other characters as well, then filter() is not required.
limit() is required to generate a random string of 10 characters. Without limit() , the stream will keep on generating integers infinitely.
mapToObj() converts integer value to corresponding character.
Both filter() and mapToObj() accept a functional interface as argument and so we can pass a Lambda expression .
Finally, collect() is used to collect the values generated by the stream into a StringBuffer using its append() method.
This StringBuffer is converted to a string with toString() method.
Range of integers provided to ints() is chosen according to ASCII values of numbers and alphabets. You can choose these according to the characters that need to be included in the string to generate.
Multiple executions of this program generate following output
Random alphanumeric string is: tCh5OTWY4v
Random alphanumeric string is: pHLjsd0ts4
Random alphanumeric string is: L82EvKMfsm
That is all on different ways to generate a random string in java. Hope the article was helpful !!
Java String methods
- Java string charAt()
- Java string compareTo()
- Java string contains()
- Java string equals()
- Java string indexOf()
- Java string length()
- Java string replaceAll()
- Java string split()
- Java string substring()
- Java string startsWith()
- Java String.format()
- Java string intern()
- Java string isLetter()