字符串与整数之间的转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/heihu_malice7/article/details/78982398

最近经常用到字符串与整数之间的转换,整理了一下,包含

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();
	}



猜你喜欢

转载自blog.csdn.net/heihu_malice7/article/details/78982398
今日推荐