JAVA - 字符串处理
public class StringUtils {
public static boolean isNullOrEmpty(String stringValue) {
return stringValue == null || stringValue.isEmpty();
}
public static String trim(String stringValue) {
return isNullOrEmpty(stringValue) ? stringValue : stringValue.trim();
}
public static String numberToHalfWidth(String stringValue) {
if (isNullOrEmpty(stringValue)) {
return stringValue;
}
return stringValue.replace('0', '0')
.replace('1', '1')
.replace('2', '2')
.replace('3', '3')
.replace('4', '4')
.replace('5', '5')
.replace('6', '6')
.replace('7', '7')
.replace('8', '8')
.replace('9', '9');
}
public static boolean equals(String stringValue, String anotherStringValue) {
if (stringValue == null && anotherStringValue == null) {
return true;
}
if (stringValue != null) {
return stringValue.equals(anotherStringValue);
}
else {
return false;
}
}
public static boolean equalsIgnoreCase(String stringValue, String anotherStringValue) {
if (stringValue == null && anotherStringValue == null) {
return true;
}
if (stringValue != null) {
return stringValue.equalsIgnoreCase(anotherStringValue);
}
else {
return false;
}
}
public static String toLowerCase(String stringValue) {
if (isNullOrEmpty(stringValue)) {
return stringValue;
}
return stringValue.toLowerCase();
}
public static String toUpperCase(String stringValue) {
if (isNullOrEmpty(stringValue)) {
return stringValue;
}
return stringValue.toUpperCase();
}
public static boolean checkIdentityCardNo(String cardNo) {
if (isNullOrEmpty(cardNo)) {
return false;
}
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);
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};
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;
return idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
return matches;
}
}