欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java隨機生成字符串的四種方式例子

 更新時間:2023年10月10日 11:20:26   作者:海深不見鯨  
這篇文章主要給大家介紹了關(guān)于Java隨機生成字符串的四種方式,隨機數(shù)在實際中使用很廣泛,比如要隨即生成一個固定長度的字符串、數(shù)字,文中給出了詳細的代碼示例,需要的朋友可以參考下

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類

下面的算法可以使用這種方法生成一個固定長度的隨機字符串。

  • 初始化一個空字符串以保存結(jié)果。
  • 創(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ù)組中的字符組成。

通過根據(jù)構(gòu)建工具添加以下依賴項,可以將Apache Commons Lang包含到您的項目中。

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>

總結(jié) 

到此這篇關(guān)于Java隨機生成字符串的四種方式的文章就介紹到這了,更多相關(guān)Java隨機生成字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot過濾器如何獲取POST請求的JSON參數(shù)

    SpringBoot過濾器如何獲取POST請求的JSON參數(shù)

    這篇文章主要介紹了SpringBoot過濾器如何獲取POST請求的JSON參數(shù)操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java如何使用ConfigurationProperties獲取yml中的配置

    Java如何使用ConfigurationProperties獲取yml中的配置

    這篇文章主要介紹了Java如何使用ConfigurationProperties獲取yml中的配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • 簡單聊一聊Spring中Bean別名的處理原理

    簡單聊一聊Spring中Bean別名的處理原理

    今天來和小伙伴們聊一聊 Spring 中關(guān)于 Bean 別名的處理邏輯,別名,顧名思義就是給一個 Bean 去兩個甚至多個名字,整體上來說,在 Spring 中,有兩種不同的別名定義方式,感興趣的小伙伴跟著小編一起來看看吧
    2023-09-09
  • Spring復雜對象創(chuàng)建的方式小結(jié)

    Spring復雜對象創(chuàng)建的方式小結(jié)

    這篇文章主要介紹了Spring復雜對象創(chuàng)建的三種方式,現(xiàn)在使用Spring如何創(chuàng)建這種類型的對象?Spring中提供了三種方法來創(chuàng)建復雜對象,需要的朋友可以參考下
    2022-01-01
  • Spring整合Mybatis具體代碼實現(xiàn)流程

    Spring整合Mybatis具體代碼實現(xiàn)流程

    這篇文章主要介紹了Spring整合Mybatis實操分享,文章首先通過介紹Mybatis的工作原理展開Spring整合Mybatis的詳細內(nèi)容,需要的小伙伴可以參考一下
    2022-05-05
  • Java三級菜單工具類實現(xiàn)方式

    Java三級菜單工具類實現(xiàn)方式

    這篇文章通過實例代碼給大家介紹Java三級菜單工具類實現(xiàn)方式,常用的三個字段,子級id、父級id、其次是數(shù)組children,本文結(jié)合實例代碼給大家介紹的非常詳細,需要的朋友參考下吧
    2024-05-05
  • 詳解Java MyBatis 插入數(shù)據(jù)庫返回主鍵

    詳解Java MyBatis 插入數(shù)據(jù)庫返回主鍵

    這篇文章主要介紹了詳解Java MyBatis 插入數(shù)據(jù)庫返回主鍵,有興趣的可以了解一下。
    2017-01-01
  • Java數(shù)據(jù)結(jié)構(gòu)之堆(優(yōu)先隊列)詳解

    Java數(shù)據(jù)結(jié)構(gòu)之堆(優(yōu)先隊列)詳解

    堆(優(yōu)先隊列)是一種典型的數(shù)據(jù)結(jié)構(gòu),其形狀是一棵完全二叉樹,一般用于求解topk問題。本文將利用Java語言實現(xiàn)堆,感興趣的可以學習一下
    2022-07-07
  • java實現(xiàn)簡單控制臺五子棋游戲

    java實現(xiàn)簡單控制臺五子棋游戲

    這篇文章主要為大家詳細介紹了java實現(xiàn)簡單控制臺五子棋游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-11-11
  • Java面試之如何獲取客戶端真實IP

    Java面試之如何獲取客戶端真實IP

    這篇文章主要給大家介紹了關(guān)于Java面試之如何獲取客戶端真實IP的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-09-09

最新評論