You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
homestay/minsu/minsuguanliw/src/main/java/com/utils/CommonUtil.java

38 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.utils;
import java.util.Random;
public class CommonUtil {
/**
* 此静态方法用于生成一个指定长度的随机字符串,可应用于需要生成随机标识、临时验证码等场景,通过传入参数来控制生成字符串的长度。
*
* @param num 用于指定要生成的随机字符串的长度参数类型为Integer即传入一个整数该整数决定了最终生成的随机字符串包含多少个字符。
* @return 返回值类型为String即返回一个按照特定规则生成的随机字符串其字符内容来源于预定义的字符集合长度由传入的参数num决定。
*/
public static String getRandomString(Integer num) {
// 定义一个包含所有可用字符的基础字符串,这里包含了小写英文字母和数字,后续将从这些字符中随机选取来组成最终的随机字符串。
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
// 创建一个Random类的实例用于生成伪随机数它将作为选取字符的随机索引依据通过其nextInt方法来获取在指定范围内的随机整数。
Random random = new Random();
// 创建一个StringBuffer对象用于高效地拼接字符相比于直接使用字符串相加操作StringBuffer在频繁拼接字符时性能更好将逐步把随机选取的字符添加到这里来构建最终的随机字符串。
StringBuffer sb = new StringBuffer();
// 通过循环来控制生成的随机字符串的长度循环次数由传入的参数num决定每次循环向字符串中添加一个随机字符。
for (int i = 0; i < num; i++) {
// 生成一个随机索引其范围是从0到base字符串的长度减1通过调用Random类的nextInt方法实现该索引将用于从base字符串中选取一个字符。
int number = random.nextInt(base.length());
// 根据生成的随机索引从base字符串中获取对应的字符并添加到StringBuffer对象sb中逐步构建随机字符串。
sb.append(base.charAt(number));
}
// 将StringBuffer对象转换为字符串并返回得到最终生成的随机字符串其长度和字符内容都符合随机生成的要求由上述逻辑决定。
return sb.toString();
}
}