1. 程式人生 > >字串與整數之間的轉換

字串與整數之間的轉換

最近經常用到字串與整數之間的轉換,整理了一下,包含

1、檢驗是否為整數

2、字串轉為整數

3、從字串中提取數字

直接上程式碼:

 /**
     * 檢查是否為INT型別,已經對空進行處理
     */
    public static boolean isInt(String str){
    	return GenericValidator.isInt(str);
    }
	
	/**
	 * 把字串轉化為整數,若轉化失敗,則返回0
	 * @param str字串
	 */
	public static int strToInt(String str) {
		if (org.apache.commons.lang3.StringUtils.isBlank(str)) {
			return 0;
		}
		try {
			if(str.startsWith("0")){
				return 0;
			}
			return Integer.parseInt(str);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 從字串中提取數字
	 */
	public static String getIntByStr(String str) {
		if(org.apache.commons.lang3.StringUtils.isBlank(str)){
			return null;
		}
		String regEx="[^0-9]";  
		Pattern p = Pattern.compile(regEx);  
		Matcher m = p.matcher(str);  
		return  m.replaceAll("").trim();
	}