工具类:StringUtil

/**
 * Test.java 2009-12-10 Copright(t)2009-2010 www.glodon.com.cn,All Rigths
 * Reserved
 */
package com.yltd.cnyun.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description
 * @author 
 * @DATE 2018年8月8日
 */
public class StringUtil {

	public static boolean isBlank(String str) {
		int strLen;
		if ((str == null) || ((strLen = str.length()) == 0) || str.toLowerCase().equals("null"))
			return true;
		for (int i = 0; i < strLen; ++i) {
			if (!(Character.isWhitespace(str.charAt(i)))) {
				return false;
			}
		}
		return true;
	}

	public static String replaceStar(String str, int start, int end) {
		int strLen;
		if ((str == null) || ((strLen = str.length()) == 0) || str.toLowerCase().equals("null"))
			return "";
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < strLen; ++i) {
			if (i < start) {
				sb.append(str.charAt(i));
			} else if (i <= end) {
				sb.append("*");
			} else {
				sb.append(str.charAt(i));
			}
		}
		return sb.toString();
	}

	/**
	 * 解决split函数的一个问题: 比如有个字符串String a =
	 * "a,b,c";那么a.split(",");返回的是一个String型的数组长度为3, 若字符串a = "a,,c"
	 * 执行a.split(",");返回的也是长度为3的字符串数组, 若a = "a,,"
	 * 执行a.split(",");此时返回的是个长度为1的字符串数组,把后面的就给去了, 如果程序中用到了后面的字符,就会引起数组越界的错误,
	 * 可以将a = "a,,"在加一个字符a = "a,,,end",这样虽然改变了数组的长度但是不会产生数组越界的错误。
	 * */
	public static String[] strSplit(String str) {

		if (StringUtil.isBlank(str))
			return null;

		if (',' == (str.charAt(str.length() - 1))) {
			str += ",END";
		}

		return str.split(",");
	}

	public static String[] strSplit(String str, int len) {

		if (StringUtil.isBlank(str))
			return new String[len];

		return strSplit(str);
	}

	/**
	 * 将2进制字符串进行按位或操作(实质是:权限值相加)
	 * */
	public static String getBinAddStr(String one, String two) {

		StringBuffer buf = new StringBuffer();

		if (one.length() != two.length())
			return null;

		for (int i = 0; i < one.length(); i++) {
			int v1 = one.charAt(i) == '1' ? 1 : 0;
			int v2 = two.charAt(i) == '1' ? 1 : 0;
			if ((v1 + v2) > 0)// 说明其中一位是1
				buf.append("1");
			else
				buf.append("0");
		}

		return buf.toString();
	}

	/**
	 * 校验是否为null或空字符 StringUtil.isNullOrEmpty()
*

* Author : luyujian *

*

* Date : 2013-8-19 *

* * @param str * @return */ public static boolean isNullOrEmpty(Object str) { return str == null || "".equals(str.toString()); } /** * 校验集合中是否存在null或空字符 StringUtil.isNullOrEmpty()
*

* Author : luyujian *

*

* Date : 2013-8-23 *

* * @param objs * @return */ public static boolean isNullOrEmpty(Object... objs) { if (objs == null || objs.length == 0) { return true; } for (Object obj : objs) { if (isNullOrEmpty(obj)) { return true; } } return false; } /** * 正则过滤字符串 StringUtil.getRegValue()
*

* Author : luyujian *

*

* Date : 2013-8-22 *

* * @param str * @param key */ public static String getRegValue(String str, String key) { if (StringUtil.isNullOrEmpty(str) || StringUtil.isNullOrEmpty(key)) { return ""; } String reg = ".*" + key + "\":\"(.*)\".*"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(str); while (matcher.find()) { return matcher.group(1); } return ""; } public static String getCommonRegValue(String str, String reg) { if (StringUtil.isNullOrEmpty(str, reg)) { return ""; } Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(str); while (matcher.find()) { return matcher.group(0); } return ""; } /** * 获得库巴品牌信息 StringUtil.getBrandRegValue()
*

* Author : luyujian *

*

* Date : 2013-8-22 *

* * @param str */ public static void getBrandRegValue(String str) { String reg = "brand_id:(\\w+),brand_name:([\u4e00-\u9fa5]+)"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.print(matcher.group(1)); System.out.print("="); System.out.print(matcher.group(2)); System.out.println(); } } /** * byte转16进制字符串 StringUtil.byte2hex()
*

* Author : luyujian *

*

* Date : 2013-8-28 *

* * @param bytes * @return */ public static String byte2hex(byte[] bytes) { StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex.toUpperCase()); } return sign.toString(); } /** * md5加密 StringUtil.encryptMD5()
*

* Author : luyujian *

*

* Date : 2013-8-28 *

* * @param data * @return * @throws IOException */ public static byte[] encryptMD5(String data) { byte[] bytes = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); bytes = md.digest(data.getBytes("utf-8")); } catch (Exception e) { e.printStackTrace(); } return bytes; } /** * URL decode StringUtil.decode()
*

* Author : luyujian *

*

* Date : 2013-8-29 *

* * @param str * @return */ public static String decode(String str) { if (StringUtil.isNullOrEmpty(str)) { return ""; } try { return URLDecoder.decode(str, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } } /** * url decode StringUtil.decode()
*

* Author : luyujian *

*

* Date : 2013-9-2 *

* * @param str * @param enc * @return */ public static String decode(String str, String enc) { if (StringUtil.isNullOrEmpty(str)) { return ""; } try { return URLDecoder.decode(str, enc); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } } /** * 生成length位随机数 * * @param length * @return */ public static String getCharAndNumr(int length) { String val = ""; Random random = new Random(); for (int i = 0; i < length; i++) { // 输出字母还是数字 String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 字符串 if ("char".equalsIgnoreCase(charOrNum)) { // 取得大写字母还是小写字母 int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; val += (char) (choice + random.nextInt(26)); } else if ("num".equalsIgnoreCase(charOrNum)) {// 数字 val += String.valueOf(random.nextInt(10)); } } return val; } /** * 对身份证,银行卡号的处理 * * @param str * @return */ public static String replcceStr(String str) { if (!StringUtils.isNotBlank(str)) { return null; } else { String pre = str.substring(0, 3); String suf = str.substring(str.length() - 4, str.length()); return pre + "************" + suf; } } /** * 去除空格 * * @param str * @return */ public static String trim(String str) { if (!StringUtils.isNotBlank(str)) { return null; } else { return str.replaceAll(" ", ""); } } /** * 用户名显示规则修改为只显示首尾各一位 中间位数统一用五位“*”替换 * * @param str * @return */ public static String replaceStar(String str) { int strLen = str.length(); if (str == null || strLen == 0 || str.toLowerCase().equals("null")) return ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < strLen; ++i) { } sb.append(str.substring(0, 1)); sb.append("*****"); sb.append(str.substring(strLen - 1, strLen)); return sb.toString(); } /** * 判断权限串中,有无给定值的权限 * */ public static boolean hasRight(String rightstr, int rcode) { if (null == rightstr || rightstr.length() < rcode) return false; return rightstr.charAt(rcode - 1) == '1'; } public static String getstrFromUrl(String urladdress, String sendstr) { StringBuffer resbu = new StringBuffer(); try { URL url = new URL(urladdress); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println(sendstr); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { resbu.append(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return resbu.toString(); } public static boolean startCheck(String reg, String string) { boolean tem = false; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(string); tem = matcher.matches(); return tem; } /** * 手机号码验证,11位,不知道详细的手机号码段,只是验证开头必须是1和位数 * */ public static boolean checkCellPhone(String cellPhoneNr) { String reg = "^[1][\\d]{10}"; return startCheck(reg, cellPhoneNr); } /** * 检查EMAIL地址 用户名和网站名称必须>=1位字符 地址结尾必须是2位以上,如:cn,test,com,info * */ public static boolean checkEmail(String email) { String regex = "\\w+\\@\\w+\\.\\w{2,}"; return startCheck(regex, email); } /*** * 字符串所在位置 * * @param substr * 长字符串 * @param str * 所查找字符串 * @param splitstr * 分隔符 * @return */ public static String getSplitIndex(String substr, String str, String splitstr) { if (isBlank(substr) || isBlank(str)) return ""; String[] strs = substr.split(","); for (int i = 0; i < strs.length; i++) { if (strs[i].equals(str)) return String.valueOf(i); } return ""; } /** * 全角转半角 * * @param input * @return */ public static String toHalfStr(String input) { char c[] = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == '\u3000') { c[i] = ' '; } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { c[i] = (char) (c[i] - 65248); } } String returnString = new String(c); return returnString; } /** * 半角转全角 * * @param input * @return */ public static String ToFullStr(String input) { char c[] = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == ' ') { c[i] = '\u3000'; // 采用十六进制,相当于十进制的12288 } else if (c[i] < '\177') { // 采用八进制,相当于十进制的127 c[i] = (char) (c[i] + 65248); } } return new String(c); } /** * 对用户输入进行清理$(美元符号) [5] %(百分比符号) [6] @(at 符号) [7] '(单引号) [8] "(引号) [9] * \'(反斜杠转义单引号) [10] \"(反斜杠转义引号) [11] <>(尖括号) [12] ()(括号) [13] +(加号) [14] * CR(回车符,ASCII 0x0d) [15] LF(换行,ASCII 0x0a) [16] ,(逗号) [17] \(反斜杠) * */ public static String replaceStr(String str) { str = str.replace("'", "‘"); str = str.replace("|", "|"); str = str.replace("&", "&"); str = str.replace(";", ";"); str = str.replace("@", "@"); str = str.replace("\"", "”"); str = str.replace("\\'", "\’"); str = str.replace("\\\"", "\\‘"); str = str.replace("<", "《"); str = str.replace(">", "》"); str = str.replace("(", "("); str = str.replace(")", ")"); str = str.replace("\\(", "("); str = str.replace("\\)", ")"); str = str.replace("+", "+"); str = str.replace("\\+", "+"); str = str.replace("\r", ""); str = str.replace("\n", ""); str = str.replace("script", " s c r i p t "); str = str.replace("SCRIPT", " s c r i p t "); str = str.replace("%27", ""); str = str.replace("%22", ""); str = str.replace("%3E", ""); str = str.replace("%3C", ""); str = str.replace("%3D", ""); str = str.replace("%2F", ""); return str; } public static String join(String separator, List strings) { if (null == strings || strings.size() == 0 || strings.isEmpty()) return null; String[] stringarray = new String[strings.size()]; for (int i = 0; i < strings.size(); i++) { stringarray[i] = strings.get(i); } return join(separator, stringarray); } public static String join(String separator, String[] stringarray) { if (stringarray == null) return null; else return join(separator, stringarray, 0, stringarray.length); } public static String join(String separator, String[] stringarray, int startindex, int count) { String result = ""; if (stringarray == null) return null; for (int index = startindex; index < stringarray.length && index - startindex < count; index++) { if (separator != null && index > startindex) result += separator; if (stringarray[index] != null) result += stringarray[index]; } return result; } public static String urlDecode(String str) { try { str = URLDecoder.decode(str, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return str; } public static String concatString(String first,String end){ StringBuffer sb=new StringBuffer(); boolean fflag=isBlank(first); boolean eflag=isBlank(end); if(!(fflag||eflag)){ sb.append(first); sb.append(","); sb.append(end); }else if(!fflag&&eflag){ sb.append(first); }else if(fflag&&!eflag){ sb.append(end); } return sb.toString(); } public static boolean hasLength(CharSequence str) { return (str != null && str.length() > 0); } public static boolean containsWhitespace(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i))) { return true; } } return false; } }

工具类:StringUtil_第1张图片

你可能感兴趣的:(工具类:StringUtil)