1. 程式人生 > >StringUtils處理工具類

StringUtils處理工具類

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class StringUtils {

	final static Logger logger = Logger.getLogger(StringUtils.class);
	public final static String ENCODING = "GBK";
	private static String[] strArray = new String[] { "a", "b", "c", "d", "e",
			"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
			"s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E",
			"F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
			"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4",
			"5", "6", "7", "8", "9", "!", "@", "#", "$", "%", "^", "&", "(",
			")" };

	/**
	 * 首字母變小寫  
	 * 
	 * @param str
	 * @return
	 */
	public static String firstCharToLowerCase(String str) {
		char firstChar = str.charAt(0);
		if (firstChar >= 'A' && firstChar <= 'Z') {
			char[] arr = str.toCharArray();
			arr[0] += ('a' - 'A');
			return new String(arr);
		}
		return str;
	}

	/**
	 * 首字母變大寫  
	 * 
	 * @param str
	 * @return
	 */
	public static String firstCharToUpperCase(String str) {
		char firstChar = str.charAt(0);
		if (firstChar >= 'a' && firstChar <= 'z') {
			char[] arr = str.toCharArray();
			arr[0] -= ('a' - 'A');
			return new String(arr);
		}
		return str;
	}

	/**
	 * 判斷是否為空  
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(final String str) {
		return (str == null) || (str.length() == 0);
	}

	/**
	 * 判斷是否不為空  
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(final String str) {
		return !isEmpty(str);
	}

	public static boolean isNullOrEmpty(String str) {
		if (str == null || "".equals(str))
			return true;
		else
			return false;

	}

	public static String nullToEmpty(String str) {
		if (str == null)
			return "";
		return str;

	}

	public static String getEscaped(String str) {
		try {
			return URLEncoder.encode(str, ENCODING);
		} catch (UnsupportedEncodingException e) {
			logger.warn("", e);
		}
		return "";
	}

	/**
	 * 校驗手機號碼  
	 * 
	 * @param num
	 * @return  
	 */
	public static boolean IsMobileCode(String code) {
		String Code = "[0-9]{3}";
		if (isNumeric(code, Code))
			return true;
		else
			return false;
	}

	public static boolean IsMobileNum1(String num) {
		String HK = "[0-9]{8}";
		String MainLand = "[0-9]{11}";
		// String USA="";
		if ((isNumeric(num, HK) == true || isNumeric(num, MainLand) == true)
				&& num.matches("^(13|15|18)\\d{9}$"))
			return true;
		else
			return false;
	}

	public static boolean IsMoblieNum(String num) {
		String Code = "[0-9]{1,4}";
		String HK = "[0-9]{8}";
		String MainLand = "[0-9]{11}";
		if (num.trim() != null || num.trim() != "") {
			String[] str = num.split(" ");
			if (isNumeric(str[0], Code)) {
				if ((isNumeric(str[1], HK) == true || isNumeric(str[1],
						MainLand) == true)
						&& str[1].matches("^(13|15|18)\\d{6,9}$")) {

					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static boolean isNumeric(String str, String where) {
		Pattern pattern = Pattern.compile(where);
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 生成唯一字串  
	 * 
	 * @param length
	 *                        需要長度
	 * @param symbol
	 *                        是否允許出現特殊字元 -- 
[email protected]
$%^&*() * @return */ public static String getUniqueString(int length, boolean symbol) throws Exception { Random ran = new Random(); int num = ran.nextInt(61); String returnString = ""; String str = ""; for (int i = 0; i < length;) { if (symbol) num = ran.nextInt(70); else num = ran.nextInt(61); str = strArray[num]; if (!(returnString.indexOf(str) >= 0)) { returnString += str; i++; } } return returnString; } /** * 判斷是否空白   * * @param str * @return */ public static boolean isBlank(final 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; } /** * 判斷是否不是空白   * * @param str * @return */ public static boolean isNotBlank(final String str) { return !isBlank(str); } /** * 判斷多個字串全部是否為空   * * @param strings * @return */ public static boolean isAllEmpty(String... strings) { if (strings == null) { return true; } for (String str : strings) { if (isNotEmpty(str)) { return false; } } return true; } /** * 判斷多個字串其中任意一個是否為空   * * @param strings * @return */ public static boolean isHasEmpty(String... strings) { if (strings == null) { return true; } for (String str : strings) { if (isEmpty(str)) { return true; } } return false; } /** * checkValue為 null 或者為 "" 時返回 defaultValue   * * @param checkValue * @param defaultValue * @return */ public static String isEmpty(String checkValue, String defaultValue) { return isEmpty(checkValue) ? defaultValue : checkValue; } /** * 字串不為 null 而且不為 "" 並且等於other   * * @param str * @param other * @return */ public static boolean isNotEmptyAndEquelsOther(String str, String other) { if (isEmpty(str)) { return false; } return str.equals(other); } /** * 字串不為 null 而且不為 "" 並且不等於other   * * @param str * @param other * @return */ public static boolean isNotEmptyAndNotEquelsOther(String str, String... other) { if (isEmpty(str)) { return false; } for (int i = 0; i < other.length; i++) { if (str.equals(other[i])) { return false; } } return true; } /** * 字串不等於other   * * @param str * @param other * @return */ public static boolean isNotEquelsOther(String str, String... other) { for (int i = 0; i < other.length; i++) { if (other[i].equals(str)) { return false; } } return true; } /** * 判斷字串不為空   * * @param strings * @return */ public static boolean isNotEmpty(String... strings) { if (strings == null) { return false; } for (String str : strings) { if (str == null || "".equals(str.trim())) { return false; } } return true; } /** * 比較字元相等   * * @param value * @param equals * @return */ public static boolean equals(String value, String equals) { if (isAllEmpty(value, equals)) { return true; } return value.equals(equals); } /** * 比較字串不相等   * * @param value * @param equals * @return */ public static boolean isNotEquals(String value, String equals) { return !equals(value, equals); } public static String[] split(String content, String separatorChars) { return splitWorker(content, separatorChars, -1, false); } public static String[] split(String str, String separatorChars, int max) { return splitWorker(str, separatorChars, max, false); } public static final String[] EMPTY_STRING_ARRAY = new String[0]; private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) { if (str == null) { return null; } int len = str.length(); if (len == 0) { return EMPTY_STRING_ARRAY; } List<String> list = new ArrayList<String>(); int sizePlus1 = 1; int i = 0, start = 0; boolean match = false; boolean lastMatch = false; if (separatorChars == null) { while (i < len) { if (Character.isWhitespace(str.charAt(i))) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else if (separatorChars.length() == 1) { char sep = separatorChars.charAt(0); while (i < len) { if (str.charAt(i) == sep) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else { while (i < len) { if (separatorChars.indexOf(str.charAt(i)) >= 0) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } if (match || (preserveAllTokens && lastMatch)) { list.add(str.substring(start, i)); } return (String[]) list.toArray(EMPTY_STRING_ARRAY); } /** * 消除轉義字元   * * @param str * @return */ public static String escapeXML(String str) { if (str == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); switch (c) { case '\u00FF': case '\u0024': break; case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '\"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: if (c >= '\u0000' && c <= '\u001F') break; if (c >= '\uE000' && c <= '\uF8FF') break; if (c >= '\uFFF0' && c <= '\uFFFF') break; sb.append(c); break; } } return sb.toString(); } /** * 將字串中特定模式的字元轉換成map中對應的值   * * @param s *             需要轉換的字串 * @param map *             轉換所需的鍵值對集合 * @return 轉換後的字串 */ public static String replace(String s, Map<String, Object> map) { StringBuilder ret = new StringBuilder((int) (s.length() * 1.5)); int cursor = 0; for (int start, end; (start = s.indexOf("${", cursor)) != -1 && (end = s.indexOf("}", start)) != -1;) { ret.append(s.substring(cursor, start)).append( map.get(s.substring(start + 2, end))); cursor = end + 1; } ret.append(s.substring(cursor, s.length())); return ret.toString(); } public static String replace(String s, Object... objs) { if (objs == null || objs.length == 0) return s; if (s.indexOf("{}") == -1) return s; StringBuilder ret = new StringBuilder((int) (s.length() * 1.5)); int cursor = 0; int index = 0; for (int start; (start = s.indexOf("{}", cursor)) != -1;) { ret.append(s.substring(cursor, start)); if (index < objs.length) ret.append(objs[index]); else ret.append("{}"); cursor = start + 2; index++; } ret.append(s.substring(cursor, s.length())); return ret.toString(); } /** * 字串格式化工具,引數必須以{0}之類的樣式標示出來.大括號中的數字從0開始。   * * @param source *             源字串 * @param params *             需要替換的引數列表,寫入時會呼叫每個引數的toString(). * @return 替換完成的字串。如果原始字串為空或者引數為空那麼將直接返回原始字串。 */ public static String replaceArgs(String source, Object... params) { if (params == null || params.length == 0 || source == null || source.isEmpty()) { return source; } StringBuilder buff = new StringBuilder(source); StringBuilder temp = new StringBuilder(); int startIndex = 0; int endIndex = 0; String param = null; for (int count = 0; count < params.length; count++) { if (params[count] == null) { param = null; } else { param = params[count].toString(); } temp.delete(0, temp.length()); temp.append("{"); temp.append(count); temp.append("}"); while (true) { startIndex = buff.indexOf(temp.toString(), endIndex); if (startIndex == -1) { break; } endIndex = startIndex + temp.length(); buff.replace(startIndex, endIndex, param == null ? "" : param); } startIndex = 0; endIndex = 0; } return buff.toString(); } public static String substringBefore(final String s, final String separator) { if (isEmpty(s) || separator == null) { return s; } if (separator.isEmpty()) { return ""; } final int pos = s.indexOf(separator); if (pos < 0) { return s; } return s.substring(0, pos); } public static String substringBetween(final String str, final String open, final String close) { if (str == null || open == null || close == null) { return null; } final int start = str.indexOf(open); if (start != -1) { final int end = str.indexOf(close, start + open.length()); if (end != -1) { return str.substring(start + open.length(), end); } } return null; } public static String substringAfter(final String str, final String separator) { if (isEmpty(str)) { return str; } if (separator == null) { return ""; } final int pos = str.indexOf(separator); if (pos == -1) { return ""; } return str.substring(pos + separator.length()); } /** * 自定義字符集轉換為位元組陣列   * * @param str * @return */ public static String toString(byte[] bytes, String type) { try { return new String(bytes, type); } catch (UnsupportedEncodingException e) { return null; } } /** * 自定義字符集轉換為位元組陣列   * * @param str * @return */ public static byte[] getBytes(String str, String type) { if (str != null) { try { return str.getBytes(type); } catch (UnsupportedEncodingException e) { return null; } } else { return null; } } public static void main(String[] a) { String escapeXML = escapeXML("\\"); System.out.println(escapeXML); try { System.out.println(getUniqueString(36, true)); System.out.println(getUniqueString(36, true)); System.out.println(getUniqueString(36, true)); System.out.println(getUniqueString(36, true)); System.out.println(getUniqueString(36, true)); System.out.println(replaceArgs("1{0}2{1}3{2}4{3}5{4}6{5}7{6}8{7}9", "a", "a", "a", "a", "a", "a", "a", "a")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

相關推薦

StringUtils處理工具

import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.ut

android ImageUtils 圖片處理工具

copy pac float can turn getconf ble static ring /** * 加入文字到圖片。相似水印文字。 * @param gContext * @param gResId * @param gText * @re

時間處理工具

nim mount minute int quest lac asn ren 問題 import java.sql.Timestamp;import java.text.ParseException;import java.text.SimpleDateFormat;i

json處理工具

package com.sys.util; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType

java常用工具(二)—— JSON處理工具

tor ast val simple sta 轉換 local pass password package com.springboot.commons.utils; import com.springboot.commons.scan.JacksonObjectMapp

java後端時間處理工具,返回 "XXX 前" 的字串

我們經常會遇到顯示 "某個之間之前" 的需求(比如各種社交軟體,在回覆訊息時,顯示xxx之前回復),我們可以在後端進行處理,也可以在前端進行處理,這裡講講在後端進行處理的方法. 其實很簡單,我們只需要將從資料庫中取到的date型別的欄位進行處理。 工具類如下: import java.

工作日處理工具(包括工作日判斷和工作日區間判斷)

  對於工作日處理相對來說還是比較簡單的,不外乎就是週末判斷和假期判斷。   不過,有些人會把它們寫死在類裡面,看以下程式碼:   耦合性較強的程式碼:       public class Weekda

圖片處理工具 util

PathUtil package util; public class PathUtil { private static String seperator = System.getProperty("file.separator"); // 獲取根目錄

手機號隱藏中間四位、使用者名稱處理、銀行卡擷取後四位等敏感資訊處理工具

在我們平常開發中,我們有時候需要對使用者名稱、手機號等資訊進行一些敏感資訊的處理(如:王小五 →王*五),還有銀行卡擷取後四位等,這裡我整理成了一個工具類,分享給大家! /** * 敏感資訊處理工具類 * @author Zhang */ public final c

StringUtils常用工具

平常我們寫程式碼是經常用到工具類,每次都要查,很麻煩,所以我搜集資料在這裡總結一下,如果有不正確或不合理的地方,還請你評論執教,謝謝 \(0_0)/ 首先,我就先說說Java中最常見的判空處理在校驗一個String為空時通常有以下幾種情況: a.是否為null b.是否為"

XML檔案處理工具 ---XMLUtils

package com.jeeplus.mobile.utils; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.

安卓--非同步處理工具(AsyncTask)

.xml程式碼如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schem

java中Excel處理工具

/** 該工具類會返回處理結果和封裝之後的資料,獲取資料直接從 **/ import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import ja

java 日期處理工具

package com.conb.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.

時間處理工具(DateUtil)

package com.lvmama.comm.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import ja

身份證號碼驗證處理工具

package com.zotech.basic.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * 身份證驗證工具類 * wulin */ publ

資料處理工具(求和,平均值,最大值,最小值。。。)

package com.szllt.pingshan.entity.data; import java.util.Date; import java.util.List; import java.util.Map; /**  * 資料處理工具類    *  */ publi

日期處理工具

package com.czqc.czc.buz.api.utils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; im

java後端時間處理工具,返回 "XXX 前" 的字符串

fcm one 處理 fill form throws sdn 之間 csdn 轉自:https://www.cnblogs.com/devise/p/9974672.html 我們經常會遇到顯示 "某個之間之前" 的需求(比如各種社交軟件,在回復消息時,顯示xxx之前回復

一個圖片處理工具

/** * 圖片處理工具類 */ public class BitMapUtils { /** * 對指定路徑圖片壓縮改變其檔案大小 * @param file * @param bitmap */ public