Random string generation

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.