APEXでランダム文字列生成

来源:互联网 发布:2017最流行的网络用语 编辑:程序博客网 时间:2024/05/22 01:05
string getRandomString(Integer LengthRequired){         String CharList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';        String Res = '';        integer position;        for(Integer i = 0; i <= LengthRequired; i++) {            position = Integer.valueof(String.valueof(Math.roundToLong(CharList.length()*Math.random()))) -1;            Res += CharList.substring(position,position+1);        }        return Res;    }


追加文字があれば、こんなかんじでしょう。/*** ランダム文字列を生成する* デフォルト:a-zA-Z0-9* @param int(ランダム文字列桁数)、str(追加文字、option)* @return string(ランダム文字列)*/public static String createRandomStr(Integer num, String str) {if(int == null || int < 1) return null;// デフォルト文字列String a = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890’;// 追加文字列if(str != null && str.length() != 0){String b = str;// 重複判断for(Integer i = 0; i < str.length(); i ++){if(a.contains(str.subString(i,i+1))) b = b.replaceAll(str.subString(i,i+1), ”);}// スペース不要a = (a + b).replaceAll(‘ ‘, ”).replaceAll(‘ ’, ”);}// ランダム文字列を生成するString ranStr = ”;List aList = a.split(”);for(Integer j = 0; j < num; j ++) {ranStr += aList[(Math.random() * a.length()).intValue() + 1];}return ranStr;}

参考

http://arrowhead.blog25.fc2.com/blog-entry-2224.html

http://sfsupport.blog.fc2.com/blog-entry-64.html

0 0
原创粉丝点击