Given a character set combination and the length of a randomly generated string, the string can be randomly generated;
For example, {'A', '..., 'z'} and length 5 are used to generate a random string of 5;
Package xiazdong. util; import Java. util. random;/* generate a random string */public class stringwidthweightrandom {private random widthrandom = new random (); Private int length; private char [] chars; private random = new random (); Public stringwidthweightrandom (char [] chars) {This. chars = chars;} // The length of the generated string. The Public String getnextstring (INT length) is generated based on the given char set) {char [] DATA = new char [length]; for (INT I = 0; I <length; I ++) {int Index = random. nextint (chars. length); Data [I] = chars [Index];} string S = new string (data); Return s ;}}
Test code:
package test.com.sap.prd.util;import junit.framework.TestCase;import org.junit.Test;import com.sap.prd.util.StringWidthWeightRandom;public class StringWidthWeightRandomTest extends TestCase {@Testpublic void testGetNextString()throws Exception{StringWidthWeightRandom random = new StringWidthWeightRandom(new char[]{'A','B','C','D','E','F','G'});for(int i=1;i<10;i++){System.out.println(random.getNextString(i));}}}
Result:
FCCEGECADACFBFCDBBCFEBFEADFAFDEEDACEEEFFGFBEG