随机字符串生成算法

IOS算法:

char data[NUMBER_OF_CHARS];
    for (int x=0;x<NUMBER_OF_CHARS;data[x++] = (char)('A' + (arc4random_uniform(26))));
    return [[NSString alloc] initWithBytes:data length:NUMBER_OF_CHARS encoding:NSUTF8StringEncoding];
 
JAVA实现:
 

给定一个字符集合,给定随机生成的字符串的长度,即可随机生成字符串;

比如{'a','.....,'z'}及长度5,则随机生成一个长度为5的字符串;

[java] view plaincopy
 
  1. package xiazdong.util;  
  2.   
  3. import java.util.Random;  
  4.   
  5. /*根据给定的char集合,生成随机的字符串*/  
  6. public class StringWidthWeightRandom {  
  7.     private Random widthRandom = new Random();  
  8.     private int length;  
  9.     private char[] chars;  
  10.     private Random random = new Random();  
  11.     public StringWidthWeightRandom(char[] chars) {  
  12.         this.chars = chars;  
  13.     }  
  14.       
  15.     //参数为生成的字符串的长度,根据给定的char集合生成字符串  
  16.     public String getNextString(int length){      
  17.           
  18.         char[] data = new char[length];  
  19.           
  20.         for(int i = 0;i < length;i++){  
  21.             int index = random.nextInt(chars.length);  
  22.             data[i] = chars[index];  
  23.         }  
  24.         String s = new String(data);  
  25.         return s;  
  26.     }  
  27.       
  28.   
  29. }  

测试代码:

[java] view plaincopy
 
  1. package test.com.sap.prd.util;  
  2.   
  3. import junit.framework.TestCase;  
  4.   
  5. import org.junit.Test;  
  6.   
  7. import com.sap.prd.util.StringWidthWeightRandom;  
  8.   
  9. public class StringWidthWeightRandomTest extends TestCase {  
  10.   
  11.     @Test  
  12.     public void testGetNextString()throws Exception{  
  13.         StringWidthWeightRandom random = new StringWidthWeightRandom(new char[]{'A','B','C','D','E','F','G'});  
  14.           
  15.         for(int i=1;i<10;i++){  
  16.             System.out.println(random.getNextString(i));  
  17.         }  
  18.     }  
  19. }  


结果:

[java] view plaincopy
 
  1. F  
  2. CC  
  3. EGE  
  4. CADA  
  5. CFBFC  
  6. DBBCFE  
  7. BFEADFA  
  8. FDEEDACE  
  9. EEFFGFBEG  
原文地址:https://www.cnblogs.com/kenshinobiy/p/4424188.html