Java隨機生成字符串的四種方式例子
java.util.UUID 類可用于生成UUID, 它的static randomUUID方法返回一個32個字符的字符串。
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("-", ""); } }
注意randomUUID方法生成的字符串包含“-”。上面的示例通過使用空字符串替換了。
以上程序輸出為:
Random string is: 923ed6ec4d04452eaf258ec8a4391a0f
Random string of 8 characters is: 923ed6ec
使用Math類
下面的算法可以使用這種方法生成一個固定長度的隨機字符串。
- 初始化一個空字符串以保存結果。
- 創(chuàng)建大小寫字母和數(shù)字的組合,以創(chuàng)建一組超級字符。
- 啟動一個循環(huán),該循環(huán)的count等于所需的隨機字符串長度。
- 在每次迭代中,生成一個介于0和超集長度之間的隨機數(shù)。
- 在步驟4中生成的數(shù)字索引處從步驟2中的字符串中提取字符,并將其添加到步驟1中的字符串中。
- 循環(huán)完成后,步驟1中的字符串將是一個隨機字符串。
示例代碼:
import java.util.Math; public class RandomStringGenerator { public static void main(String[] args) { String randomString = usingMath(10); System.out.println("Random string is: " + randomString); } static String usingMath(int length) { 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 < length; 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(); } }
以上程序輸出為:
Random string is: kqNG2SYHeF
Random string is: lCppqqUg8P
Random string is: GGiFiEP5Dz
這種方法使您能夠更好地控制需要包含在隨機字符串中的字符。例如,如果您不想要數(shù)字,那么就從超集中刪除它們。如果您想要特殊字符,那么就在超集中添加一組特殊字符。
使用Random類
此方法與Math方法類似,即創(chuàng)建所有字符的超集,生成一個隨機索引,并使用該索引處的字符創(chuàng)建最終字符串。
這種方法使用java.util.Random 類生成隨機索引。
示例代碼:
import java.util.Random; public class RandomStringGenerator { public static void main(String[] args) { String randomString = usingRandom(10); System.out.println("Random string is: " + randomString); } static String usingRandom(int length) { 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 < length; 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(); } }
以上程序輸出為:
Random string is: TycOBOxITs
Random string is: 7LLWVbg0ps
Random string is: p6VyqdO6bT
您還可以使用java.util.SecureRandom類生成一個隨機整數(shù)。它是java.util.Random的一個子類。
使用RandomStringUtils類
Apache Commons Lang庫有一個org.apache.commons.lang.RandomStringUtils類,該類具有生成固定長度的隨機字符串的方法。
它的方法可以生成只包含字母(隨機字母)、數(shù)字(隨機數(shù)字)或兩者(隨機字母數(shù)字)的隨機字符串。
所有這些方法都接受一個整數(shù)參數(shù),該參數(shù)表示它們將生成的字符串的長度。
示例代碼:
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); } }
以上程序輸出為:
Random string of 10 alphabets: OEfadIYfFm
Random string of 10 numbers: 1639479195
Random string of 10 alphanumeric characters: wTQRMXrNY9
該類還有一個方法random,該方法接受一個整數(shù)(即要生成的字符串的長度)和一個char數(shù)組。生成的隨機字符串僅由該數(shù)組中的字符組成。
通過根據構建工具添加以下依賴項,可以將Apache Commons Lang包含到您的項目中。
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
總結
到此這篇關于Java隨機生成字符串的四種方式的文章就介紹到這了,更多相關Java隨機生成字符串內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot過濾器如何獲取POST請求的JSON參數(shù)
這篇文章主要介紹了SpringBoot過濾器如何獲取POST請求的JSON參數(shù)操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Java如何使用ConfigurationProperties獲取yml中的配置
這篇文章主要介紹了Java如何使用ConfigurationProperties獲取yml中的配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02