public class StringUtils { private StringUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 判断字符串是否为空 * * @param value * @return {@code true}: 空<br> {@code false}: 不为空 */ public static boolean isEmpty(String value) { return (value == null || "".equalsIgnoreCase(value.trim()) || "null".equalsIgnoreCase(value.trim())); } /** * 判断字符串是否为null或全为空格 * * @param s 待校验字符串 * @return {@code true}: null或全空格<br> {@code false}: 不为null且不全空格 */ public static boolean isTrimEmpty(String s) { return (s == null || s.trim().length() == 0); } /** * 判断字符串是否为null或全为空白字符 * * @param s 待校验字符串 * @return {@code true}: null或全空白字符<br> {@code false}: 不为null且不全空白字符 */ public static boolean isSpace(String s) { if (s == null) return true; for (int i = 0, len = s.length(); i < len; ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } /** * 判断两字符串是否相等 * * @param a 待校验字符串a * @param b 待校验字符串b * @return {@code true}: 相等<br>{@code false}: 不相等 */ public static boolean equals(CharSequence a, CharSequence b) { if (a == b) return true; int length; if (a != null && b != null && (length = a.length()) == b.length()) { if (a instanceof String && b instanceof String) { return a.equals(b); } else { for (int i = 0; i < length; i++) { if (a.charAt(i) != b.charAt(i)) return false; } return true; } } return false; } /** * 判断两字符串忽略大小写是否相等 * * @param a 待校验字符串a * @param b 待校验字符串b * @return {@code true}: 相等<br>{@code false}: 不相等 */ public static boolean equalsIgnoreCase(String a, String b) { return a == null ? b == null : a.equalsIgnoreCase(b); } /** * null转为长度为0的字符串 * * @param s 待转字符串 * @return s为null转为长度为0字符串,否则不改变 */ public static String null2Length0(String s) { return s == null ? "" : s; } /** * 返回字符串长度 * * @param s 字符串 * @return null返回0,其他返回自身长度 */ public static int length(CharSequence s) { return s == null ? 0 : s.length(); } /** * 首字母大写 * * @param s 待转字符串 * @return 首字母大写字符串 */ public static String upperFirstLetter(String s) { if (isEmpty(s) || !Character.isLowerCase(s.charAt(0))) return s; return String.valueOf((char) (s.charAt(0) - 32)) + s.substring(1); } /** * 首字母小写 * * @param s 待转字符串 * @return 首字母小写字符串 */ public static String lowerFirstLetter(String s) { if (isEmpty(s) || !Character.isUpperCase(s.charAt(0))) return s; return String.valueOf((char) (s.charAt(0) + 32)) + s.substring(1); } /** * 反转字符串 * * @param s 待反转字符串 * @return 反转字符串 */ public static String reverse(String s) { int len = length(s); if (len <= 1) return s; int mid = len >> 1; char[] chars = s.toCharArray(); char c; for (int i = 0; i < mid; ++i) { c = chars[i]; chars[i] = chars[len - i - 1]; chars[len - i - 1] = c; } return new String(chars); } /** * 转化为半角字符 * * @param s 待转字符串 * @return 半角字符串 */ public static String toDBC(String s) { if (isEmpty(s)) return s; char[] chars = s.toCharArray(); for (int i = 0, len = chars.length; i < len; i++) { if (chars[i] == 12288) { chars[i] = ' '; } else if (65281 <= chars[i] && chars[i] <= 65374) { chars[i] = (char) (chars[i] - 65248); } else { chars[i] = chars[i]; } } return new String(chars); } /** * 转化为全角字符 * * @param s 待转字符串 * @return 全角字符串 */ public static String toSBC(String s) { if (isEmpty(s)) return s; char[] chars = s.toCharArray(); for (int i = 0, len = chars.length; i < len; i++) { if (chars[i] == ' ') { chars[i] = (char) 12288; } else if (33 <= chars[i] && chars[i] <= 126) { chars[i] = (char) (chars[i] + 65248); } else { chars[i] = chars[i]; } } return new String(chars); } /** * 正则:手机号(精确) * <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p> * <p>联通:130、131、132、145、155、156、175、176、185、186</p> * <p>电信:133、153、173、177、180、181、189</p> * <p>全球星:1349</p> * <p>虚拟运营商:170</p> */ // private static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$"; private static final String REGEX_MOBILE_EXACT = "[1][3456789]\\d{9}"; /** * 正则:URL */ private static final String REGEX_URL = "[a-zA-z]+://[^\\s]*"; /** * 验证手机号(精确) * * @param input 待验证文本 * @return {@code true}: 匹配<br>{@code false}: 不匹配 */ public static boolean isMobileNum(CharSequence input) { return isMatch(REGEX_MOBILE_EXACT, input); } /** * 验证URL * * @param input 待验证文本 * @return {@code true}: 匹配<br>{@code false}: 不匹配 */ public static boolean isURL(CharSequence input) { return isMatch(REGEX_URL, input); } /** * 判断是否匹配正则 * * @param regex 正则表达式 * @param input 要匹配的字符串 * @return {@code true}: 匹配<br>{@code false}: 不匹配 */ public static boolean isMatch(String regex, CharSequence input) { return input != null && input.length() > 0 && Pattern.matches(regex, input); } /** * 判断是否是正确的金额格式 * * @param money * @return */ public static boolean isNumber(String money) { if (!isEmpty(money) && !money.startsWith(".")) { Pattern p = Pattern.compile("^(\\d+)(\\.\\d{0,3})?.*$"); Matcher m = p.matcher(money); return m.matches(); } return false; } /** * 匹配是否是全数字 * * @param num * @return */ public static boolean isNumerical(String num) { if (!isEmpty(num)) { Pattern p = Pattern.compile("^\\d+$"); Matcher m = p.matcher(num); return m.matches(); } return false; } /** * 判断字符串中是否包数字 * * @param num * @return */ public static boolean isContainNumerical(String num) { if (!isEmpty(num)) { Pattern p = Pattern.compile("^(?=.*[a-zA-Z])(?=.*[0-9]).*$"); Matcher m = p.matcher(num); return m.matches(); } return false; } /** * 匹配小数点后两位(0.05) * * @param str * @return */ public static boolean isBigDecimal(String str) { Matcher match = null; if (isNumeric(str) == true) { Pattern pattern = Pattern.compile("[0-9]*"); match = pattern.matcher(str.trim()); } else { if (str.trim().indexOf(".") != -1) { Pattern pattern = Pattern.compile("^[0-9]+\\.[1-9]|[0-9]+\\.[0-9][0-9]$"); match = pattern.matcher(str.trim()); } } return match.matches(); } public static boolean is2Decimal(String str) { Matcher match = null; if (isNumeric(str) == true) { Pattern pattern = Pattern.compile("[0-9]*"); match = pattern.matcher(str.trim()); } else { if (str.trim().indexOf(".") != -1) { Pattern pattern = Pattern.compile("^\\d+(\\.\\d{1,2})?$"); match = pattern.matcher(str.trim()); } } return match.matches(); } /** * 判断是否是纯数字 * * @param str * @return */ public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); return isNum.matches(); } /** * 是否是纯字母 * * @param str * @return */ public static boolean isLetters(String str) { Pattern pattern = Pattern.compile("^[A-Za-z]+$"); Matcher isNum = pattern.matcher(str); return isNum.matches(); } /** * 判断email格式是否正确 * * @param email * @return */ public static boolean isEmail(String email) { // String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; //新的正则校验 // String str = "^([a-zA-Z0-9_&'.+*# \\-])+@(([a-zA-Z0-9_&'.+*# \\-])+\\.)+([a-zA-Z0-9]{2,63})$"; //与react native 保持一致 String str = "^([a-zA-Z0-9_&'.+*#-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,63})$"; Pattern p = Pattern.compile(str); Matcher m = p.matcher(email); return m.matches(); } /** * 判断用户名格式是否正确 * * @param userName * @return */ public static boolean isUserName(String userName) { String str = "^[A-Za-z0-9\\u4e00-\\u9fa5]\\w{2,19}$"; Pattern p = Pattern.compile(str); Matcher m = p.matcher(userName); return m.matches(); } /** * 获得当前日期和时间 * * @return 2014-07-22 10:59:05 */ public static String getCurrentDateAndTime() { return getCurrentTime("yyyy-MM-dd HH:mm:ss"); } public static String getCurrentTime(String format) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault()); String currentTime = sdf.format(date); return currentTime; } // 获取当期时间格式为: yyyymmddhhmmss public static String getDate() { return getCurrentTime("yyyyMMdd HHmmss"); } /** * 生成订单号 * * @return */ public static String getOrderid() { return getCurrentTime("yyyyMMddHHmmss") + Math.round(Math.random() * 9000 + 1000); } public static String genOutTradNo() { return String.valueOf(System.currentTimeMillis() / 1000); } /** * 获得当前日期(年) * * @return 2014 */ public static String getCurrentYear() { return getCurrentTime("yyyy"); } /** * 获得当前日期(月) * * @return 2014-12 */ public static String getCurrentMonth() { return getCurrentTime("yyyy-MM"); } /** * 获得当前日期(月) * * @return 2014-12-24 */ public static String getCurrentDay() { return getCurrentTime("yyyy-MM-dd"); } /** * 截取卡号 123456*****8888 * * @param cardNo * @return */ public static String trimCardNo(String cardNo) { if (cardNo != null && !"".equals(cardNo)) { if (cardNo.length() > 9) { String header = cardNo.substring(0, 6); String tail = cardNo.substring(cardNo.length() - 4, cardNo.length()); int len = cardNo.length() - (header.length() + header.length()); StringBuilder sb = new StringBuilder(); sb.append(header); for (int i = 0; i <= len; i++) { sb.append("*"); } sb.append(tail); return sb.toString(); } } return null; } /** * 截取卡号 123456*****8888 * * @param cardNo * @return */ public static String trimCardNoList(String cardNo) { if (cardNo != null && !"".equals(cardNo)) { if (cardNo.length() >= 16) { String tail = cardNo.substring(cardNo.length() - 4, cardNo.length()); StringBuilder sb = new StringBuilder(); // sb.append(header); // for (int i = 0; i <= len; i++) { // sb.append("*"); // } sb.append("**** **** **** "); sb.append(tail); return sb.toString(); } } return null; } /** * 截取卡号 1234 56** ***8 888 * * @param cardNo * @return */ public static String trimCard(String cardNo) { StringBuilder sb = new StringBuilder(cardNo); int length = cardNo.length() / 4 + cardNo.length(); for (int i = 0; i < length; i++) { if (i % 5 == 0) { sb.insert(i, " "); } } sb.deleteCharAt(0); return sb.toString(); } /** * 截身份证号 1**************8 * * @param IdNo * @return */ public static String trimIdNo(String IdNo) { if (IdNo != null && !"".equals(IdNo)) { if (IdNo.length() > 9) { String header = IdNo.substring(0, 1); String tail = IdNo.substring(IdNo.length() - 1, IdNo.length()); int len = IdNo.length() - (header.length() + header.length()); StringBuilder sb = new StringBuilder(); sb.append(header); for (int i = 0; i <= len; i++) { sb.append("*"); } sb.append(tail); return sb.toString(); } } return null; } /** * 截取卡号 后4位 * * @param cardNo * @return */ public static String trimCardNoBehind4(String cardNo) { if (cardNo != null && !"".equals(cardNo)) { String tail = cardNo.substring(cardNo.length() - 4, cardNo.length()); return tail; } return null; } /** * 格式化金额(例如:500.00) * * @param money 金额 * @return 如果返回null,金额格式错误 */ public static String formatMoney(String money) { String result = money; try { if (isEmpty(money) || "0".equals(money) || "0.0".equals(money)) { return "0.00"; } DecimalFormat myformat = new DecimalFormat(); myformat.applyPattern("##,###.######"); return myformat.format(Double.parseDouble(money)); } catch (Exception e) { e.printStackTrace(); return result; } } /** * 格式化数字(例如:500,000) * * @param number 数字 * @return 如果返回null,金额格式错误 */ public static String formartNumber(String number) { String result = number; try { if (isEmpty(number)) { return "0"; } DecimalFormat myformat = new DecimalFormat(); myformat.applyPattern("##,###.######"); return myformat.format(Double.parseDouble(number)); } catch (Exception e) { e.printStackTrace(); return result; } } /** * 格式化数字(例如:500,000) * * @param number 数字 * @return 如果返回null,金额格式错误 */ public static String formartNumber(int number) { try { DecimalFormat myformat = new DecimalFormat(); myformat.applyPattern("##,###.######"); return myformat.format(number); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 把字符串转换成html标签 * * @param context * @param resStrID * @param text * @return */ public static Spanned str2html(Context context, int resStrID, String text) { String str = String.format(context.getResources().getString(resStrID), text); return Html.fromHtml(str); } /** * 判断多个字符串是否相等,如果其中有一个为空字符串或null,则返回false,只有全相等才返回true */ public static boolean isEquals(String... agrs) { String last = null; for (int i = 0; i < agrs.length; i++) { String str = agrs[i]; if (isEmpty(str)) { return false; } if (last != null && !str.equalsIgnoreCase(last)) { return false; } last = str; } return true; } /** * 转换大金额单位 * * @param money 金额 * @param unit 换算单位 * @return */ public static String convertMoneyUnit(double money, int unit) { String unitStr = null; if (money > 0 && unit >= 1) { if (money < 1000) { unitStr = String.valueOf(money + "千"); } else if (money < 10 * 1000) { unitStr = String.valueOf(money + "万"); } else if (money < 100 * 10000) { unitStr = String.valueOf(money + "千万"); } else if (money < 10000 * 100000) { unitStr = String.valueOf(money + "千万"); } } return unitStr; } /** * 格式化文件大小 */ public static String formatFileSize(long len) { return formatFileSize(len, false); } public static String formatFileSize(long len, boolean keepZero) { String size; DecimalFormat formatKeepTwoZero = new DecimalFormat("#.00"); DecimalFormat formatKeepOneZero = new DecimalFormat("#.0"); if (len < 1024) { size = String.valueOf(len + "B"); } else if (len < 10 * 1024) { // [0, 10KB),保留两位小�? size = String.valueOf(len * 100 / 1024 / (float) 100) + "KB"; } else if (len < 100 * 1024) { // [10KB, 100KB),保留一位小�? size = String.valueOf(len * 10 / 1024 / (float) 10) + "KB"; } else if (len < 1024 * 1024) { // [100KB, 1MB),个位四舍五�? size = String.valueOf(len / 1024) + "KB"; } else if (len < 10 * 1024 * 1024) { // [1MB, 10MB),保留两位小�? if (keepZero) { size = String.valueOf(formatKeepTwoZero.format(len * 100 / 1024 / 1024 / (float) 100)) + "MB"; } else { size = String.valueOf(len * 100 / 1024 / 1024 / (float) 100) + "MB"; } } else if (len < 100 * 1024 * 1024) { // [10MB, 100MB),保留一位小�? if (keepZero) { size = String.valueOf(formatKeepOneZero.format(len * 10 / 1024 / 1024 / (float) 10)) + "MB"; } else { size = String.valueOf(len * 10 / 1024 / 1024 / (float) 10) + "MB"; } } else if (len < 1024 * 1024 * 1024) { // [100MB, 1GB),个位四舍五�? size = String.valueOf(len / 1024 / 1024) + "MB"; } else { // [1GB, ...),保留两位小�? size = String.valueOf(len * 100 / 1024 / 1024 / 1024 / (float) 100) + "GB"; } return size; } /** * 截取字符串(手机号,银行卡,邮箱),省略部分用 * 代替 * * @param number * @return */ public static String payinfoTrim(String number) { Pattern pattern = Pattern.compile("[0-9]*"); boolean isNumber = pattern.matcher(number).matches(); if (isNumber) {// 判断是否为电话号或者银行卡 if (number.length() >= 16) {// 判断是否为银行卡 return bankcardTrim(number); } else { return phoneTrim(number); } } else { if (isEmail(number)) {// 判断是否为邮箱格式 return emailTrim(number); } else { return number; } } } /** * 截取电话号码,如:156****4119 * * @param phone 电话号码 * @return */ public static String phoneTrim(String phone) { if (!isEmpty(phone) && phone.length() >= 11) { return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); } return phone; } /** * 截银行卡号码,如:201304********3445 * * @param bankcard * @return */ public static String bankcardTrim(String bankcard) { int length = bankcard.length(); if (length >= 16) { return bankcard.subSequence(0, 6) + "********" + bankcard.substring(length - 4, length); } return bankcard; } /** * 截取邮箱,如:lix****@163.com * * @param email 邮箱号 * @return */ public static String emailTrim(String email) { if (!isEmpty(email)) { int lastIndex = email.lastIndexOf("@"); String emailSub = email.substring(0, lastIndex); if (emailSub.length() > 4) { return email.replace(email.substring(lastIndex - 4, lastIndex), "****"); } else { return email.replace(emailSub, "****"); } } return email; } /** * 时间字符串转换格式(yyyy年MM月dd日) * * @param str1 * @return */ public static String dateTransfer(String str1) { String newD = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); try { Date date = format.parse(str1); format = new SimpleDateFormat("yyyy年MM月dd日"); newD = format.format(date); } catch (Exception e) { e.printStackTrace(); } return newD; } /** * 获取当前时间 */ public static String getYearMonthDay() { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Date curDate = new Date(System.currentTimeMillis());// 获取当前时间 String str = formatter.format(curDate); return str; } /** * 校验护照 */ public static boolean checkoutPassport(String passport) { Pattern pattern = Pattern.compile("[a-zA-Z][0-9]{7,8}"); boolean isPassport = pattern.matcher(passport).matches(); return isPassport; } /** * 实现文本复制功能 * add by wangqianzhou * * @param content */ public static void copy(String content, Context context) { // 得到剪贴板管理器 ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); cmb.setText(content.trim()); } /** * 实现粘贴功能 * add by wangqianzhou * * @param context * @return */ public static String paste(Context context) { // 得到剪贴板管理器 ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); return cmb.getText().toString().trim(); } // 获取手机系统版本 public static String getLocalSystemVersion() { String version = android.os.Build.VERSION.RELEASE; if (version == null) { version = ""; } return version; } public static String getStringResource(int id) { return MyApplication.getContext().getResources().getString(id); } /** * 提取出城市或者县 * * @param city * @param district * @return */ public static String extractLocation(final String city, final String district) { return district.contains("县") ? district.substring(0, district.length() - 1) : city.substring(0, city.length() - 1); } /** * 判断是否由数字、英文、英文+数字组成 * * @param str * @return */ public static boolean isDightOrletter(String str) { Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$"); Matcher isNum = pattern.matcher(str); return isNum.matches(); } /** * 验证手机格式 */ public static boolean isMobile(String number) { String num = "[1][3456789]\\d{9}"; if (TextUtils.isEmpty(number)) { return false; } else { //matches():字符串是否在给定的正则表达式匹配 return number.matches(num); } } // 判断一个字符串是否含有数字 private static boolean hasDigit(String content) { boolean flag = false; Pattern p = Pattern.compile(".*\\d+.*"); Matcher m = p.matcher(content); if (m.matches()) { flag = true; } return flag; } /** * 该方法主要使用正则表达式来判断字符串中是否包含大写字母 */ private static boolean judgeContainsStr(String cardNum) { String regex = ".*[A-Z]+.*"; Matcher m = Pattern.compile(regex).matcher(cardNum); return m.matches(); } /** * 该方法主要使用正则表达式来判断字符串中是否包含小写字母 */ private static boolean judgeContainsStrs(String cardNum) { String regex = ".*[a-z]+.*"; Matcher m = Pattern.compile(regex).matcher(cardNum); return m.matches(); } /** * 判断是否包含大小写以及数字 */ public static boolean isPWD(String pwd) { if (hasDigit(pwd) && judgeContainsStr(pwd) && judgeContainsStrs(pwd) && pwd.length() >= 8) { return true; } else { return false; } } /** * float四舍五入保留小数点n位 * * @param count 保留几位 */ public static float floatChange(String data, int count) { if (!data.equals("")) { BigDecimal b = new BigDecimal(data); float f1 = b.setScale(count, BigDecimal.ROUND_DOWN).floatValue(); return f1; } else { return 0; } } /** * float四舍五入保留小数点n位 * * @param count 保留几位 */ public static float floatChange(float data, int count) { BigDecimal b = new BigDecimal(data); float f1 = b.setScale(count, BigDecimal.ROUND_HALF_UP).floatValue(); return f1; } /** * 保留8位小数 */ public static String saveFloat8(String df) { double d = (new Double(df)).doubleValue(); DecimalFormat decimalFormat = new DecimalFormat("###.0000"); String s = decimalFormat.format(d) + ""; return s; } /** * 保留小数点8位 */ public static String saveFloat(float f) { DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(8); // 设置最大小数位 String result = df.format(f); return result; } /** * 去除科学计算法 * * @param num * @return */ public static String doubleTrans2(float num) { NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(6); String is = formatter.format(num); return is; } /** * 去除科学计算法 * * @param num * @return */ public static String doubleTrans2(double num, int count) { NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(count); String is = formatter.format(num); return is; } /** * 向下取整 保留小数点n位并去除科学计数法 */ public static String saveFloorXCount(Float f, int count) { // double value = Math.floor(f); BigDecimal b = new BigDecimal(f); float f1 = b.setScale(count, BigDecimal.ROUND_DOWN).floatValue(); NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(count); String is = formatter.format(f1); return is; } /** * 向下取整 保留小数点n位并去除科学计数法 */ public static String saveFloorXCount(String f, int count) { // double value = Math.floor(f); if(StringUtils.isEmpty(f)){ f="0"; } BigDecimal b = new BigDecimal(f); BigDecimal f1 = b.setScale(count, BigDecimal.ROUND_HALF_DOWN); NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(count); String is = formatter.format(f1); return is; } }