apache.commons.text生成随机字符串

apache.commons.text生成随机字符串

本文使用到的第三方jar包为:commons-text-1.8.jar

另外:使用此包还需要引入lang3包(依赖lang3):commons-lang3-3.8.1.jar
下载地址:https://commons.apache.org/proper/commons-text/download_text.cgi
说明书:https://commons.apache.org/proper/commons-text/apidocs/index.html

导包:(只使用到RandomStringGenerator工具类,所以只导下面的的包)

import org.apache.commons.text.RandomStringGenerator;

如果未引入依赖包,则会报下列异常:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/Validate

Apache commons text 是一个专注于处理字符串的算法的库。
org.apache.commons.text包下有一个类:RandomStringGenerator.Builder,该类用于生成RandomStringGenerator实例的生成器。
该类提供了 build(),withinRange(char[]… pairs)等成员方法
build():使用指定的属性构建RandomStringGenerator。
withinRange(char[]… pairs)指定生成的字符串中允许的最小和最大字符的数组。
生成字符串代码如下:


import org.apache.commons.text.RandomStringGenerator;

public class RandomStringTest {
    public static void main(String[] args) {

        /**
         * 随机生成字符串
         */
        RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange(new char[]{'\u4e00', '\u9fa5'}).build();
				 // withinRange() 指定生成的字符串的区间
                //.withinRange(new char[]{'a', 'z'}, new char[]{'A', 'Z'}, new char[]{'0', '9'}).build();
				   // '\u4e00', '\u9fa5':这是指中文区间
				   //'a', 'z':这是字母区间a-z
        // 生成长度为10的随机字符串
        System.out.println(generator.generate(10));
    }
}

运行结果:(此处是生成随机中文:’\u4e00’, ‘\u9fa5’)

灁挫欷耵螳帰鶽赠麜讦

(ps:一个字都不认识)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值