public class StringUtils {
/**
* 判断字符串是否为空
* 为空则返回true,否则返回false
* @param str
* @return
*/
public static boolean isEmpty(String str){
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))){
return false;
}
}
return true;
}
public static String getRandomString(int length){
//产生随机数
Random random=new Random();
StringBuffer sb=new StringBuffer();
//循环length次
for(int i=0; i<length; i++){
//产生0-2个随机数,既与a-z,A-Z,0-9三种可能
int number=random.nextInt(3);
long result=0;
switch(number){
//如果number产生的是数字0;
case 0:
//产生A-Z的ASCII码
result=Math.round(Math.random()*25+65);
//将ASCII码转换成字符
sb.append(String.valueOf((char)result));
break;
case 1:
//产生a-z的ASCII码
result=Math.round(Math.random()*25+97);
sb.append(String.valueOf((char)result));
break;
case 2:
//产生0-9的数字
sb.append(String.valueOf(new Random().nextInt(10)));
break;
}
}
return sb.toString();
}
public static boolean isPhone(String phone){
String check = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(phone);
return matcher.matches();
}
public static boolean isNum(String key){
Pattern digit = Pattern.compile("\\d+");
return digit.matcher(key).matches();
}
public static boolean isCard(String cardNo){
String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
"(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
boolean matches = cardNo.matches(regularExpression);
//判断第18位校验值
if (matches) {
if (cardNo.length() == 18) {
try {
char[] charArray = cardNo.toCharArray();
//前十七位加权因子
int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
//这是除以11后,可能产生的11位余数对应的验证码
String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
int sum = 0;
for (int i = 0; i < idCardWi.length; i++) {
int current = Integer.parseInt(String.valueOf(charArray[i]));
int count = current * idCardWi[i];
sum += count;
}
char idCardLast = charArray[17];
int idCardMod = sum % 11;
if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
return true;
} else {
System.out.println("身份证最后一位:" + String.valueOf(idCardLast).toUpperCase() +
"错误,正确的应该是:" + idCardY[idCardMod].toUpperCase());
return false;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("异常:" + cardNo);
return false;
}
}
}
return matches;
}
public static String byteToHex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException(
"Argument b ( byte array ) is null! ");
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xff);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
网友评论