本文主要是介绍java产生随机字符串的各种方法------工具类(包含过滤表情方法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.不多说直接上代码,看注释,代码 如下:
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class CharacterUtil
{private static Random strGen = new Random();;private static Random numGen = new Random();;private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();;private static char[] numbers = ("0123456789").toCharArray();;/**
* 产生随机字符串(可以指定长度)
* */
public static final String randomString(int length){if (length < 1){return null;}char[] randBuffer = new char[length];for (int i = 0; i < randBuffer.length; i++){randBuffer[i] = numbersAndLetters[strGen.nextInt(61)];}return new String(randBuffer);}/**
* 产生随机数值字符串 (可以指定长度)
* */public static final String randomNumStr(int length){if (length < 1){return null;}char[] randBuffer = new char[length];for (int i = 0; i < randBuffer.length; i++){randBuffer[i] = numbers[numGen.nextInt(9)];}return new String(randBuffer);}/*** emojiFilter* @Description: 过滤emoji表情* @param source* @return*/public static String emojiFilter(String source)
{if (source != null){Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);Matcher emojiMatcher = emoji.matcher(source);if (emojiMatcher.find()){source = emojiMatcher.replaceAll("*");return source;}return source;}return source;}/*** 字符串转换unicode*/public static String string2Unicode(String string){StringBuffer unicode = new StringBuffer();for (int i = 0; i < string.length(); i++){// 取出每一个字符char c = string.charAt(i);// 转换为unicodeunicode.append("\\u" + Integer.toHexString(c));}return unicode.toString();}/*** unicode 转字符串*/public static String unicode2String(String unicode){StringBuffer string = new StringBuffer();String[] hex = unicode.split("\\\\u");for (int i = 1; i < hex.length; i++){// 转换出每一个代码点int data = Integer.parseInt(hex[i], 16);// 追加成stringstring.append((char) data);}return string.toString();}}
这篇关于java产生随机字符串的各种方法------工具类(包含过滤表情方法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!