工具类篇【一】String字符串

前言

String是Java编程中最常使用的数据类型之一,或者说是java.lang包中的最常使用的元素之一,String 字符串既能作为基本数据类型存储在数据库中,又能作为大文本结构展示在前端,还能方便得跟其他数据类型(如:int、long、Double、BigDecimal等)快速转换。也能把Date转换为各种各样的格式。

一、常用方法

截取字符串方法

str原字符串

val从字符串的下标位置开始截取

    /**
	 * @author 
	 * @DateTime 2017年12月5日 下午7:56:25
	 *
	 * @param str
	 * @param val
	 * @return
	 */
	public static String subStr(String str, int val) {

		String returnValue = str;
		if (StringUtils.isNotEmpty(str) && str.length() > val) {

			returnValue = str.substring(0, val);

		} else {
			returnValue = str;
		}

		return returnValue;
	}

截取字符串方法

str大字符串

spc要截取的包含的字符串

	public static List<String> splitString(String str, String spc) {

		if (str == null || str.isEmpty() || spc == null || spc.isEmpty()) {
			return null;
		}

		List<String> strList = new ArrayList<String>();
		String[] sts = str.split(spc);

		for (String string : sts) {
			strList.add(string.toString());
		}

		return strList;
	}

空字符串判断方法

	public static boolean isEmpty(String str) {

		if (str == null || str.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

查询某子字符(串)在母字符串中出现的次数

    /** 查证字符串出现的次数
	 *  @author 
	 *	@DateTime 2018年6月12日 上午10:53:22
	 *
	 *  @param srcText
	 *  @param findText
	 *  @return
	 */
	public static int appearNumber(String srcText, String findText) {
		int count = 0;
		int index = 0;
		while ((index = srcText.indexOf(findText, index)) != -1) {
			index = index + findText.length();
			count++;
		}
		return count;
	}

截取字符串方法

从起始位置截取到截止位置

str:字符串

beginIndex:开始的索引位置

endIndex:结束的索引位置

注意:前开后闭原则

	/**
	 *  按起始位置截取字符串,不包含最后一位
	 *  @author 
	 *	@DateTime 2019年2月21日 下午6:02:57
	 *
	 *  @param str
	 *  @param beginIndex
	 *  @param endIndex
	 *  @return
	 */
	public static String subStrByLocation(String str, int beginIndex, int endIndex) {

		try {
			return str.substring(beginIndex, endIndex);
		} catch (Exception e) {
			log.info("",e);
			return "";
		}
	}

String转为int

	public static int StringToInt(String str) {

		try {
			if (str.isEmpty()) {
				return 0;
			} else {
				return Integer.valueOf(str);
			}
		} catch (Exception e) {
			log.info("StringToInt error---->" + e);
			return 0;
		}

	}

猜你喜欢

转载自blog.csdn.net/Follow_24/article/details/108760876