public class StringUtils { private static final String _BR = "<br/>"; // 全局数组 private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; /** * 提取出城市或者县 * @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 cardId * @return */ public static boolean checkBankCard(String cardId) { char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1)); if(bit == 'N'){ return false; } return cardId.charAt(cardId.length() - 1) == bit; } /** * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 * @param nonCheckCodeCardId * @return */ public static char getBankCardCheckCode(String nonCheckCodeCardId){ if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0 || !nonCheckCodeCardId.matches("\\d+")) { //如果传的不是数据返回N return 'N'; } char[] chs = nonCheckCodeCardId.trim().toCharArray(); int luhmSum = 0; for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) { int k = chs[i] - '0'; if(j % 2 == 0) { k *= 2; k = k / 10 + k % 10; } luhmSum += k; } return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0'); } /** * md5 加密 * * @param plainText * @return */ public static String toMD5(String plainText) { String resultString = null; try { resultString = new String(plainText); MessageDigest md = MessageDigest.getInstance("MD5"); try { resultString = byteToString(md.digest(plainText.getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return resultString; } /** * 转换字节数组为16进制字串 * * @param bByte * @return */ private static String byteToString(byte[] bByte) { StringBuffer sBuffer = new StringBuffer(); for (int i = 0; i < bByte.length; i++) { sBuffer.append(byteToArrayString(bByte[i])); } return sBuffer.toString(); } /** * 返回形式为数字跟字符串 * * @param bByte * @return */ private static String byteToArrayString(byte bByte) { int iRet = bByte; // System.out.println("iRet="+iRet); if (iRet < 0) { iRet += 256; } int iD1 = iRet / 16; int iD2 = iRet % 16; return strDigits[iD1] + strDigits[iD2]; } private static SimpleDateFormat format_date = new SimpleDateFormat("yyyy-MM-dd"); private static SimpleDateFormat format_datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm"); /** * 转化时间格式 * * @param time * @return */ public static String formatDate(String time) { try { return format_date.format(Long.parseLong(time)); } catch (NumberFormatException e) { e.printStackTrace(); } return null; } /** * 转化时间格式 * * @param time * @return */ public static String formatDateTime(String time) { try { return format_datetime.format(Long.parseLong(time)); } catch (NumberFormatException e) { e.printStackTrace(); } return null; } /** * 金钱格式转换 * * @param amount * @return */ public static String formatAmount(String amount) { String format; try { DecimalFormat df = new DecimalFormat("0.00"); double d = Double.parseDouble(amount); double result = d ; format = df.format(result); return format + ""; } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "0"; } /** * 获取两个日期的时间差 */ public static int getTimeInterval(String data) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); int interval = 0; try { Date currentTime = new Date();// 获取现在的时间 Date beginTime = dateFormat.parse(data); interval = (int) ((beginTime.getTime() - currentTime.getTime()) / (1000));// 时间差 // 单位秒 } catch (ParseException e) { e.printStackTrace(); } return interval; } /** * 设定显示文字 */ public static String getInterval(long interval) { String txt = null; if (interval >= 0) { long day = interval / (24 * 3600);// 天 long hour = interval % (24 * 3600) / 3600;// 小时 long minute = interval % 3600 / 60;// 分钟 long second = interval % 60;// 秒 txt = "距离现在还有:" + day + "天" + hour + "小时" + minute + "分" + second + "秒"; } else { new AlertDialog.Builder(null).setTitle("温馨提示") .setMessage("您输入的时间小于当前时间,请重新输入。") .setPositiveButton("确定", null).show(); } return txt; } /** * 判断字符串是否为空 * * @return true:不为空, false:为空 */ public static boolean isNotNull(String str) { if (str != null && !"".equals(str)) { return true; } return false; } public static boolean isEmpty(String str) { if (str != null && !"".equals(str)) { return false; } return true; } /** * 校验用户名是否合法,规则4-20个字符(可以为字母、数字或下划线'_',不能包含空格) * * @param name * 用户名 * @return true为合法 */ public static boolean checkName(String name) { Pattern pattern = Pattern.compile("^[0-9a-zA-Z_]{4,20}$"); Matcher matcher = pattern.matcher(name); return matcher.matches(); } /** * 校验密码是否合法,规则密码由6~16位数字或字母组成。 * * @param psw * 用户名 * @return true为合法 */ public static boolean checkPsw(String psw) { Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{6,16}$"); Matcher matcher = pattern.matcher(psw); return matcher.matches(); } /** * 转换数据类型; * * @param id * 编号 * @return string 4位编号,如0101 */ public static String unformatVid(String id) { int _id = Integer.parseInt(id); return String.valueOf(_id); } /** * 转换输入流为字符串 * * @param is * 指定要转换的输入流 * @return String 字符串 */ public static String getString(InputStream is) { BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = ""; try { while ((line = in.readLine()) != null) { buffer.append(line); } } catch (IOException e) { e.printStackTrace(); return null; } return buffer.toString(); } /** * 检查是否是邮箱 * * @param email * @return */ public static boolean isEmail(String email) { if (email == null || email.trim().length() == 0) return false; Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); return emailer.matcher(email).matches(); } /** * string转int * * @param string * @param defaultValue * @return */ public static int toInt(String string, int defaultValue) { if (string == null || string.equals("")) { return defaultValue; } try { return Integer.parseInt(string); } catch (NumberFormatException err) { return defaultValue; } } /** * string转Float * * @param string * @param defaultValue * @return */ public static float toFloat(String string, float defaultValue) { if (string == null || string.equals("")) { return defaultValue; } try { return Float.parseFloat(string); } catch (NumberFormatException err) { return defaultValue; } } /** * string转Long * * @param string * @param defaultValue * @return */ public static long toLong(String string, long defaultValue) { if (string == null || string.equals("")) { return defaultValue; } try { return Long.parseLong(string); } catch (NumberFormatException err) { return defaultValue; } } /** * string 转 boolean * * @param string * @param defaultValue * @return */ public static boolean toBoolean(String string, boolean defaultValue) { if (string == null || string.equals("")) { return defaultValue; } try { return Boolean.parseBoolean(string); } catch (NumberFormatException err) { return defaultValue; } } /** * 字符串数组转字符串,并用逗号分隔 * * @param strArray * @return */ public static String arrayToString(String[] strArray) { if (strArray == null || strArray.length == 0) { return ""; } StringBuffer s = new StringBuffer(); int len = strArray.length; for (int i = 0; i < len; i++) { s.append(strArray[i]); if (i >= 0 && i < len - 1) { s.append(','); } } return s.toString(); } /** * 字符串截取 * * @param str * @param length * @return * @throws Exception */ public static String subString(String str, int length) throws Exception { byte[] bytes = str.getBytes("Unicode"); int n = 0; // 表示当前的字节数 int i = 2; // 要截取的字节数,从第3个字节开始 for (; i < bytes.length && n < length; i++) { // 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节 if (i % 2 == 1) { n++; // 在UCS2第二个字节时n加1 } else { // 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节 if (bytes[i] != 0) { n++; } } } // 如果i为奇数时,处理成偶数 if (i % 2 == 1) { // 该UCS2字符是汉字时,去掉这个截一半的汉字 if (bytes[i - 1] != 0) i = i - 1; // 该UCS2字符是字母或数字,则保留该字符 else i = i + 1; } return new String(bytes, 0, i, "Unicode"); } /** * 分割字符串 * * @param str * String 原始字符串 * @param splitsign * String 分隔符 * @return String[] 分割后的字符串数组 */ public static String[] split(String str, String splitsign) { int index; if (str == null || splitsign == null) return null; ArrayList<String> al = new ArrayList<String>(); while ((index = str.indexOf(splitsign)) != -1) { al.add(str.substring(0, index)); str = str.substring(index + splitsign.length()); } al.add(str); return (String[]) al.toArray(new String[0]); } /** * 替换字符串 * * @param from * String 原始字符串 * @param to * String 目标字符串 * @param source * String 母字符串 * @return String 替换后的字符串 */ public static String replace(String from, String to, String source) { if (source == null || from == null || to == null) return null; StringBuffer bf = new StringBuffer(""); int index = -1; while ((index = source.indexOf(from)) != -1) { bf.append(source.substring(0, index) + to); source = source.substring(index + from.length()); index = source.indexOf(from); } bf.append(source); return bf.toString(); } /** * 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号) * * @param str * String 原始字符串 * @return String 替换后的字符串 */ public static String htmlencode(String str) { if (str == null) { return null; } return replace("\"", """, replace("<", "<", str)); } /** * 替换字符串,将被编码的转换成原始码(替换成双引号和小于号) * * @param str * String * @return String */ public static String htmldecode(String str) { if (str == null) { return null; } return replace(""", "\"", replace("<", "<", str)); } /** * 在页面上直接显示文本内容,替换小于号,空格,回车,TAB * * @param str * String 原始字符串 * @return String 替换后的字符串 */ public static String htmlshow(String str) { if (str == null) { return null; } str = replace("<", "<", str); str = replace(" ", " ", str); str = replace("\r\n", _BR, str); str = replace("\n", _BR, str); str = replace("\t", " ", str); return str; } /** * 返回指定字节长度的字符串 * * @param str * String 字符串 * @param length * int 指定长度 * @return String 返回的字符串 */ public static String toLength(String str, int length) { if (str == null) { return null; } if (length <= 0) { return ""; } try { if (str.getBytes("GBK").length <= length) { return str; } } catch (Exception ex) { } StringBuffer buff = new StringBuffer(); int index = 0; char c; length -= 3; while (length > 0) { c = str.charAt(index); if (c < 128) { length--; } else { length--; length--; } buff.append(c); index++; } buff.append("..."); return buff.toString(); } /** * 获取url的后缀名 * * @param urlString * @return */ public static String getUrlFileName(String urlString) { String fileName = urlString.substring(urlString.lastIndexOf("/")); fileName = fileName.substring(1, fileName.length()); if (fileName.equalsIgnoreCase("")) { Calendar c = Calendar.getInstance(); fileName = c.get(Calendar.YEAR) + "" + c.get(Calendar.MONTH) + "" + c.get(Calendar.DAY_OF_MONTH) + "" + c.get(Calendar.MINUTE); } return fileName; } public static String replaceSomeString(String str) { String dest = ""; try { if (str != null) { str = str.replaceAll("\r", ""); str = str.replaceAll(">", ">"); str = str.replaceAll("“", "“"); str = str.replaceAll("”", "”"); str = str.replaceAll("'", "'"); str = str.replaceAll(" ", ""); str = str.replaceAll("<br\\s*/>", "\n"); str = str.replaceAll(""", "\""); str = str.replaceAll("<", "<"); str = str.replaceAll("‘", "《"); str = str.replaceAll("’", "》"); str = str.replaceAll("·", "·"); str = str.replace("—", "—"); str = str.replace("…", "…"); str = str.replace("&", "×"); str = str.replaceAll("\\s*", ""); str = str.trim(); str = str.replaceAll("<p>", "\n "); str = str.replaceAll("</p>", ""); str = str.replaceAll("<div.*?>", "\n "); str = str.replaceAll("</div>", ""); dest = str; } } catch (Exception e) { // TODO: handle exception } return dest; } /** * 清除文本里面的HTML标签 * * @param htmlStr * @return */ public static String delHTMLTag(String htmlStr) { String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 Log.v("htmlStr", htmlStr); try { Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 } catch (Exception e) { // TODO: handle exception } return htmlStr; // 返回文本字符串 } public static String delSpace(String str) { if (str != null) { str = str.replaceAll("\r", ""); str = str.replaceAll("\n", ""); str = str.replace(" ", ""); } return str; } /** * 以友好的方式显示时间 * * @param sdate * @return */ public static String friendly_time(String sdate) { Date time = toDate(sdate); if (time == null) { return "Unknown"; } String ftime = ""; Calendar cal = Calendar.getInstance(); // 判断是否是同一天 String curDate = dateFormater2.get().format(cal.getTime()); String paramDate = dateFormater2.get().format(time); if (curDate.equals(paramDate)) { int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000); if (hour == 0) ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前"; else ftime = hour + "小时前"; return ftime; } long lt = time.getTime() / 86400000; long ct = cal.getTimeInMillis() / 86400000; int days = (int) (ct - lt); if (days == 0) { int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000); if (hour == 0) ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前"; else ftime = hour + "小时前"; } else if (days == 1) { ftime = "昨天"; } else if (days == 2) { ftime = "前天"; } else if (days > 2 && days <= 10) { ftime = days + "天前"; } else if (days > 10) { ftime = dateFormater2.get().format(time); } return ftime; } public static String trimmy(String str) { String dest = ""; if (str != null) { str = str.replaceAll("-", ""); str = str.replaceAll("\\+", ""); dest = str; } return dest; } public static String replaceBlank(String str) { String dest = ""; if (str != null) { Pattern p = Pattern.compile("\r"); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } /** * 将字符串转位日期类型 * * @param sdate * @return */ public static Date toDate(String sdate) { try { return dateFormater.get().parse(sdate); } catch (ParseException e) { return null; } } /** * 判断给定字符串时间是否为今日 * * @param sdate * @return boolean */ public static boolean isToday(String sdate) { boolean b = false; Date time = toDate(sdate); Date today = new Date(); if (time != null) { String nowDate = dateFormater2.get().format(today); String timeDate = dateFormater2.get().format(time); if (nowDate.equals(timeDate)) { b = true; } } return b; } /** * 对象转整数 * * @param obj * @return 转换异常返回 0 */ public static int toInt(Object obj) { if (obj == null) return 0; return toInt(obj.toString(), 0); } /** * 对象转整数 * * @param obj * @return 转换异常返回 0 */ public static long toLong(String obj) { try { return Long.parseLong(obj); } catch (Exception e) { } return 0; } /** * 字符串转布尔值 * * @param b * @return 转换异常返回 false */ public static boolean toBool(String b) { try { return Boolean.parseBoolean(b); } catch (Exception e) { } return false; } /** * 判断是不是合法手机 handset 手机号码 */ public static boolean isHandset(String handset) { try { if (!handset.substring(0, 1).equals("1")) { return false; } if (handset == null || handset.length() != 11) { return false; } String check = "^[0123456789]+$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(handset); boolean isMatched = matcher.matches(); if (isMatched) { return true; } else { return false; } } catch (RuntimeException e) { return false; } } /** * 判断输入的字符串是否为纯汉字 * * @param str * 传入的字符窜 * @return 如果是纯汉字返回true,否则返回false */ public static boolean isChinese(String str) { Pattern pattern = Pattern.compile("[\u0391-\uFFE5]+$"); return pattern.matcher(str).matches(); } /** * 判断是否为数字 * * @param str * @return */ public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; } return true; } /** * 判断是否为整数 * * @param str * 传入的字符串 * @return 是整数返回true,否则返回false */ public static boolean isInteger(String str) { Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); return pattern.matcher(str).matches(); } /** * 判断是否为浮点数,包括double和float * * @param str * 传入的字符串 * @return 是浮点数返回true,否则返回false */ public static boolean isDouble(String str) { Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$"); return pattern.matcher(str).matches(); } /** * 判断是否是指定长度的字符串 * * @param text * 字符串 * @param lenght * 自定的长度 * @return */ public static boolean isLenghtStrLentht(String text, int lenght) { if (text.length() <= lenght) return true; else return false; } /** * 是否是短信的长度 * * @param text * @return */ public static boolean isSMSStrLentht(String text) { if (text.length() <= 70) return true; else return false; } /** * 判断手机号码是否正确 * * @param phoneNumber * @return */ /** * 一个散列方法,改变一个字符串(如URL)到一个散列适合使用作为一个磁盘文件名。 */ public static String hashKeyForDisk(String key) { String cacheKey; try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(key.getBytes()); cacheKey = bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { cacheKey = String.valueOf(key.hashCode()); } return cacheKey; } private static String bytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } public static int convertToInt(String str) throws NumberFormatException { int s, e; for (s = 0; s < str.length(); s++) if (Character.isDigit(str.charAt(s))) break; for (e = str.length(); e > 0; e--) if (Character.isDigit(str.charAt(e - 1))) break; if (e > s) { try { return Integer.parseInt(str.substring(s, e)); } catch (NumberFormatException ex) { throw new NumberFormatException(); } } else { throw new NumberFormatException(); } } public static String getRequestUrl(String url, Map<String, String> m) { if (StringUtils.isNotNull(url) && m != null) { Map.Entry<String, String> map = null; String params = ""; Iterator<Map.Entry<String, String>> it; it = m.entrySet().iterator(); while (it.hasNext()) { map = it.next(); params += params = "&" + map.getKey() + "=" + map.getValue(); } params = params.replaceFirst("&", "?"); url += params; return url.replaceAll(" ", "%20"); } else { return null; } } public static String getStarString2(String content, int frontNum, int endNum) { if (frontNum >= content.length() || frontNum < 0) { return content; } if (endNum >= content.length() || endNum < 0) { return content; } if (frontNum + endNum >= content.length()) { return content; } String starStr = ""; for (int i = 0; i < (content.length() - frontNum - endNum); i++) { starStr = starStr + "*"; } String st = content.substring(0, frontNum) + starStr + content.substring(content.length() - endNum, content.length()); return st; } }
字符串操作工具包
最新推荐文章于 2021-09-30 12:40:12 发布