Generate random string android

Содержание
  1. How to generate a Random alpha-numeric String ?
  2. How to generate a random String in Java [duplicate]
  3. 7 Answers 7
  4. Java – Генерация Случайной Строки
  5. 1. Сгенерируйте Случайную Неограниченную Строку С Помощью Простой Java
  6. Дальнейшее чтение:
  7. Эффективный калькулятор частоты слов на Java
  8. Java – Случайные длинные, Плавающие, целочисленные и двойные
  9. Руководство по пулу строк Java
  10. 2. Сгенерируйте Случайную Ограниченную Строку С Помощью Простой Java
  11. 3. Сгенерируйте Случайную Алфавитную Строку С Помощью Java 8
  12. 4. Сгенерируйте Случайную Буквенно-Цифровую Строку С Помощью Java 8
  13. 5. Сгенерируйте Ограниченную Случайную Строку С Помощью Apache Commons Lang
  14. 6. Создайте Алфавитную Строку С Помощью Apache Commons Lang
  15. 7. Сгенерируйте Буквенно-Цифровую Строку С Помощью Apache Commons Lang
  16. 8. Заключение
  17. Generate Random String in Java
  18. Generate Random String in Java With the Regular Expression
  19. Generate Random Alphanumeric String in Java Using the Math.random() Method
  20. Generating Using Charset
  21. Use Apache Commons Lang
  22. How to generate random alpha and numeric string
  23. 3 Answers 3

How to generate a Random alpha-numeric String ?

When you develop some applications in Java or on Android platform, you can sometimes need to generate a random alpha-numeric String to generate a session id, a unique temporary id or simply to generate sample string data. Use cases are multiples and to make that there are a lot of possibilities.

In the following of this tutorial, we’re going to see several solutions that you can use. Don’t hesitate to leave me your solutions in comments.

Solution 1

In first solution, you can use a custom algorithm and use Random class from Java standard API like this :

With that solution, you can choose the characters used in String generated by changing DATA content. However, this solution uses Random class so if it’s used to generate passwords from a server, it might be vulnerable to attacks.

To call the static method you can write this :


Solution 2

With the second solution, you can choose to use a third-party library like Apache Commons for Java and its RandomStringUtils class which you can access Javadoc here : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html

Solution with RandomStringUtils is very simple :


Solution 3

A few people think about it, but use UUID class from Java standard SDK is a very convenient method to achieve the problem. Solution is simple :

In addition of the concision of the solution, a major benefit of UUID solution it is almost impossible to have 2 strings generated that collide. Wikipedia tells us what is the the risk to have duplicates in probability :

“only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%”


Solution 4

Last solution presented here is also the most expensive in generation time because it uses SecureRandom Java class. But thanks to SecureRandom Java class that chooses a number of bits from a cryptographical secure random bit generator, this solution is secure to generate passwors on a server for example.

Code is like this :

Most secure random and also most expensive because there is a big initialisation time.

Multiple solutions exist, so you must choose solution that is the most adapted to your needs.

Источник

How to generate a random String in Java [duplicate]

I have an object called Student , and it has studentName , studentId , studentAddress , etc. For the studentId , I have to generate random string consist of seven numeric charaters, eg.

Читайте также:  Обои для андроид овервотч

And I have to make sure that there is no duplicate id.

7 Answers 7

Generating a random string of characters is easy — just use java.util.Random and a string containing all the characters you want to be available, e.g.

Now, for uniqueness you’ll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.

This is very nice:

There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.

You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.

I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.

The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.

Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable or HashMap containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you’re in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).

Источник

Java – Генерация Случайной Строки

Генерируйте ограниченные и неограниченные случайные строки, используя простую Java и библиотеку Apache Commons Lang.

Автор: Eugen Paraschiv
Дата записи

В этом уроке мы покажем, как сгенерировать случайную строку в Java – сначала с помощью стандартных библиотек Java, затем с помощью варианта Java 8 и, наконец, с помощью библиотеки Apache Commons Lang .

Эта статья является частью серии “Java – Back to Basic” здесь, на Baeldung.

1. Сгенерируйте Случайную Неограниченную Строку С Помощью Простой Java

Давайте начнем с простого и сгенерируем случайную Строку , ограниченную 7 символами:

Имейте в виду, что новая строка не будет чем-то отдаленно буквенно-цифровым.

Дальнейшее чтение:

Эффективный калькулятор частоты слов на Java

Java – Случайные длинные, Плавающие, целочисленные и двойные

Руководство по пулу строк Java

2. Сгенерируйте Случайную Ограниченную Строку С Помощью Простой Java

Далее – давайте рассмотрим создание более ограниченной случайной строки; мы собираемся сгенерировать случайную Строку , используя строчные буквы алфавита и заданную длину:

3. Сгенерируйте Случайную Алфавитную Строку С Помощью Java 8

Теперь давайте использовать Random.ints – добавлено в JDK 8 – для создания алфавитной строки:

4. Сгенерируйте Случайную Буквенно-Цифровую Строку С Помощью Java 8

А затем мы можем расширить наш набор символов, чтобы получить буквенно-цифровую строку :

Обратите внимание на использование метода filter выше, чтобы исключить символы Юникода между 65 и 90 – чтобы избежать символов вне диапазона.

Читайте также:  Все китайские самсунги андроиды

5. Сгенерируйте Ограниченную Случайную Строку С Помощью Apache Commons Lang

Библиотека Commons Lang от Apache очень помогает при генерации случайных строк. Давайте посмотрим на создание ограниченной строки с использованием только букв :

Поэтому – вместо всего низкоуровневого кода в примере Java-это делается с помощью простой однострочной строки.

6. Создайте Алфавитную Строку С Помощью Apache Commons Lang

Еще один очень простой пример – на этот раз ограниченная Строка только с буквенными символами, но без передачи логических флагов в API:

7. Сгенерируйте Буквенно-Цифровую Строку С Помощью Apache Commons Lang

И, наконец, – та же случайная ограниченная Строка , но на этот раз – числовая:

И вот у нас есть это – создание ограниченных и неограниченных строк с помощью простой Java, варианта Java 8 или библиотеки Apache Commons.

8. Заключение

С помощью различных методов реализации мы смогли генерировать связанные и несвязанные строки, используя обычную Java, вариант Java 8 или библиотеку Apache Commons.

В этих примерах Java мы использовали java.util.Random , но один момент, о котором стоит упомянуть, заключается в том, что он не является криптографически безопасным. Рассмотрите возможность использования java.security.SecureRandom вместо этого для приложений, чувствительных к безопасности.

Реализацию всех этих примеров и фрагментов можно найти в проекте GitHub . Это проект на основе Maven, поэтому его должно быть легко импортировать и запускать.

Источник

Generate Random String in Java

An alphanumeric string contains numeric and alphabetical characters. In Java, there are numerous cases where alphanumeric strings are utilized. For instance, in generating a password after the user registers on an application; in generating a primary key entry to identify an element in a database; in generating session ids, among others.

This article will discuss four methods to generate a random alphanumeric string in Java.

  1. the regular expression
  2. the Math.random() method
  3. the Charset
  4. Apache Commons Lang

Generate Random String in Java With the Regular Expression

This method is easy and gives an alphanumerical string that contains uppercase in lowercase characters and digits.

The first thing is to take chars that are between 0 and 256.

The second step is to filter the chars to be left with the elements we want to include in our random String. Keep in mind that the chars we want to remain with are 0-9, and A-Z, so we can create a filter that removes all the other chars.

The next step involves selecting the random chars and adding them to a StringBuffer . We then create a String from the StringBuffer using the toString() method.

Below is a sample code.

Generate Random Alphanumeric String in Java Using the Math.random() Method

It involves creating a string that contains all the possible characters manually. We then create a random String of defined length by selecting characters and digits from the string we created previously.

First, we defined the two variables that we will need — the StringBuilder and String . The String will contain all letters of the alphabet as uppercase and digits 0-9. This string should have no symbol or space because the indexes of the characters in the string will be used to select characters randomly.

Читайте также:  Как подключить модем китайскому андроиду

Secondly, define the iteration that is limited to the length of the random string we want to create.

Third, generate a random index using the Math.random() method. Get the character from the previously created string that is the index’s position generated randomly and append it to the StringBuilder . Then we can get the random string from the StringBuilder by using the toString() method.

Below is a sample code.

Generating Using Charset

We use the Charset, which is in the java.nio.charset package. A charset stands for character set and represents a mapping between characters and numbers. The process of creating an alphanumeric string using Charset is explained below.

The first step is to take chars between 0 and 256. The Random() method is then applied to the array of the characters above. The third step is to check whether each char is alphabetic or numeric by iteration. If it is either of them, we add that character to the end of the string until we get to the defined length. The characters appended to the StringBuilder are converted to the desired string using the toString() method.

Below is a sample code.

Use Apache Commons Lang

This is the easiest method to implement because a third party handles the implementation, in this case, the Apache package.

The Apache Commons Lang package provides many helper utilities related to string manipulation in Java. Because it is a third party, it must first be added as a dependency in the project.

Источник

How to generate random alpha and numeric string

I want to generate alpha and numeric random password, i have two switches, one for alpha and one for numeric when both switches are on at that time generated string in alpha and numeric also but when my password length will be 4 so some time it’s showing only in alpha but i want in digit and also in alpha.

my code is look like below

3 Answers 3

Try following code:

Here is good example of generating secure random alpha and numeric string using SecureRandom

import java.security.SecureRandom; import java.math.BigInteger;

Here is example how to generate string with custom length.

You pass in the pool of letters to select from without distinguishing between letters and digits. If you want to ensure both are included, then you need to keep them separate for longer.

The TextView parameter is a needless complication and belongs somewhere in the calling GUI code, rather than in this utility method. You can add it back in if you have to.

This version picks a letter if switchLetters is checked and picks a digit if switchNumbers is checked, ensuring at least one of each selected type is picked. The rest of the characters are random.

Because the first two characters are in a specific order, the result is securely shuffled. That is why I used an array to hold the result, so it was easier to shuffle.

I have put in a lot of comments to help explain things.

Источник

Оцените статью